Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ac1b2fbc4b | |||
| f381e7a634 | |||
| 6a0322570b | |||
| dc4b1934e1 | |||
| aabace1bba | |||
| f7101800cd | |||
| c9f5006727 | |||
| 942a39b0eb | |||
| b2681d1236 | |||
| 63bc6e9cd8 | |||
| 7a2494c156 |
@@ -0,0 +1 @@
|
||||
False
|
||||
@@ -0,0 +1 @@
|
||||
a3dd8e4b-8c69-4536-b080-24506bc95dea
|
||||
@@ -0,0 +1 @@
|
||||
614d490d-41ba-47f9-ae3a-b56948b3d6e4
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRTS2/jIBD+Kxbn4GKMMfatbVJtVHUbtdHuam8wjBtUF0cY96Eq/32Fk6rbve0FoREz8714J14/IWnJ+X6/ekYfR7Ig0c0lzrikTFHOtky1jLeszouS84pVv8mCuGt8Iy2pBUABDdISJVJhWUVN2QG1FpuCFZbxSqSZ+mEk7TvRLrf47ADzYfyBYXSDJy356bwdXtJu7XLoh8nmYehx7ceoPSQwy9X99fZ2Q69q+X11cXF8OeKYBuTOkpY0tWClQKQSTE1FozhVNXDKhIamKysrJRzbnI8YvO7z0T5+YrBD9Bih5Tkvc0Z5Qw4LYnXUCbbRI27f9gnJLNMy1Rdzeb627+QZA2n54kPQ47gz6N3Z02gm19uz4xn1+JiY7sOwxxAdzrrMVPteRzf47LTpsnfoI1mQ2/ts0+vYDeHpi1j3R/7r/6C/TdtXrwhTRHs5TD6SliiyIDcads5jtl6SlshCWNEwS0VhNBV111CNpaamko1QprQSk6mXg4/OT8M0Zmsf8SHM8ElLrnQ/4hH4eYCdiwhxConTL5kaN2GwE8TsU/2C5SwvGU9NU9xPMbtD6wJCxMRuG6bTvH9auOSMJShTCOhjttFxl33T4y49sLWtgCPaojQ1Mx1WyqpKQW2lVLIDUQEriwqEgLIzttHGNCVwwTsjsJZkQTCZnc35KpRSHVea1lpzKjgIqroCqdbAFGssGmO/6Jjd9qlPl9YqFIYqkA0VVSmpYYpRLiomDTSVxRSlD0lO3ovkyTUGj/1flG8chGEcupidQpB9EeFu8unvZnMgXpynr7PaywEeMWTJLe18iunJoMPhcPgDAAD//wMANAV6ewIEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACoyUW2/cNhCF/4rAZ1GmSIq6vMVeGzXcZJ3sJi36xstoTVgmFyTl1DD2vxfUruts0oe+CdTozMczZ/SKnHwCNKAP+/31M7gUUYmSXY4ooQKTDlOyJd1A6EDaqhesJkz8hUpk7+AFDajlWte6B8xAAOaGNFixUWNjoK9JbQhteNaUu4iGVyRtZeDZaqh8/AYhWu/QgP6wzvjvube0lZ78bKrgJ7h1MUmnM8zqenO3Xd/jm1Z8ur68PFZGiFmgsgYNSNW17EwjcF03BvNaU9y3jGEqemWgFbJm5viZdQmCk1MVzeM7g/HJQdIDrSirCKY9OpTIyCQztpIRti/7TLLYtMrn5XK8PA6v6BkCGmj5ZuhR7kJP9uIpqtlO5mLyu511uyvvRrubg0y5cYn2we8hJAuLQetN8c5Uk4pUVFBCUIk+Sv1gHRS3q2I95RtLZkwHXOFOix7zhgmsSEcw5Q0RSveNgQx5B8HB9IPqR6uDj35Mxcn34qzPlXfJutnPsbh1CXYn0AHdyClCLphDAJeKe5keit9kfMikpjWNpgCmZqolaoSmM13T6dYI0YlR80YTVjeac81GZXqpVM805XRUHFqBSrSF8GSdnH73u1328t9+5y9WMMp5Shs/hyUZ0TyiEl1aJ8PLseJrBHOq+nQcxpvSEqhpWi5UnOZ5NVlw6cxfNCBRc8N7koOkJObt2GMJTGLViJ53ihkBOdb3wZtZp59HxghFJfoyu7xKxW0e1nfr8N+C/4T6AxvkXBVLlDWlou17jrUWNeYjUbiDusGCj20vteAUGCrRyutHCEWel7TuTGy9KT4E/WAT6DSHfM0/l97rTXE/yTT68HS2dus57edUfAFjA+gEmWIb5ix1Yyf4Bfbt3icPeXfMTfRvtd8gKB9tyr+Iz7OFbPDmuK6LHf9zW88035n+MxF5I+bk0eFwOPwDAAD//wMA4rnczdgEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACoxUyW7jOBD9FYFnUaFEagXmkHYSjJFJ24jdM4O5cSnGRGTSoKikgyD/3qAst51GH+ZGFGt59epVvSPL94A6dH043L6ADQNKUTCTqSBFhUmDC7IlTUeKjrRZTeuqKcl/KEXmHt5Qh2omZS5bwBQqwEyREguqJVYK2pzkihQlizn504C6d8RNpuDFSMjc8Df4wTiLOvSPscq9xtrcZLJ3o8q862Fph8CtjGBubjf329Ua39XV19svX46eAwwxQWYU6pDIc96ossJ5XirMclngtqYUF1UrFNQVz6k6hhkbwFveZ4N6PmNQLlgIsiuygmYEFy36SJHigUfYgg+wfTtEJBNNN9GeTubp2b2jF/CoK9ITocd0V7I3V/tBjKZXV4H7Jwja8z28Ov8ML7xHKTp4dwAfDEz8rDbJGVJOMpIVVUEIStEDlztjIVneJKs+NsypUg0wgRtZtZiVtMKCNAQXrCSVkG2pIGK8B2+hv8j6YKR3g9MhmWlPPtVZOBuMHd04JEsb4MnzcIy74/0AKEXrUfRm2D0CV29b9zjGPzv2sZfF6D3YkKx52CV/8mEXm1C1KmUBoHIqaiI0lI1qykbWqqqaSktWSkLzUjImqRaq5UK0VBas0IJBXaEUrcZwGMOJ/+8XILbe7Pegzgi2E8frngft/H6pwAajTRzNyWMSVd9PXSVzzkVvwIZPJKMOVTlTrCVRTIJjVusWc6Aci7JqWSOoqiBKe+GsNk/jT56I1opRXTZNJVqREyh03TBSa0GU1FS2qhRQFzWpG2haSYgoWd6IVhIFecmiSNfeqVGGX6VASYFS9DjauKHJMrb9aiz+XrEzI2vvgpOujwMzPWzehgD7301t4fYHN5gQ+9fzaL8N8OBs/J1vwMzZHHztwoUzxEVIpt2ThNCa1hoXguWYcU1wW0mGCa1bqrnQTOQoRTdOPoNPosK4sdNQTqJabZJrL3cmgAyjj6X/nbo6zvPutDNnQrKvt9uF83B9OKSz9Y+XNosKXm2SkwA+3ZZvQ/TeuSF2Efx4oaMN9PoE60JNR+Elj6CMBxmmr+0xcObodwq79sFoLsMQ1+AvJydhzEqbXX6tdzGAn9HH4hdDmEUxZ2LNlGe6gJMU/tcB/Pj4+PgBAAD//wMAI6jx6vUFAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSTS2/VMBCF/0rkdZz6HSc7aIuoKmhFK0Ds/Jj0Wk3tK8cpoOr+d+Tciwrs2EWjmfF3zpm8oGieAI3ozX5/+QyxLKhFJWwlRpjCRGNG7okeCRup6jSTgvb0G2pRuIafaES9cI66ATAHBVh4IrHlk8Pew0AJ9YRJUXeahwWNL8iEzsNzcNCl5TPkJaSIRvQlRJ++17dN6NycVt/lNMNVXIqJrsJcXN5d39/c4ne9+nj59u2xc4GlLuiCRyOylBrtpcKUSo8FdQwPPeeYqcF66JWh3B/HQiyQo5m7xT++MvhUIhQ3so7xjmA2oEOLvCmmYluzwP3PfSXZbLqo9XYrb5/jC3qGjEbW/jb0uO7MzeHMpacnE/3ZFGJYdqhF+5z2kEuAzZJN5TybElJsTo+czwFiQS26uWtuZ1OmlJ/+8unuKP3qP5R/MG4XIjRXF2hEigovBlLbrcGinwZsgBtspRqEttwrqLGdp1hCXNO6NFexwEPeKNGI3pl5gSPfm+x2oYAra67oX1UdhB+hnCdfCxS16DYnv7rSvNpNSUc6TljdsZb9WppP4EMGV6Bqus/raf0/I0wxQirZmjPE0tyasmvem2VXG3zvpWMAnnLbEzuB1F5L7XqvlFaTE9IRTqUTwvHJ+sFYO3DHBJusgF5V7ppusx0UcZJPWmssnOJYSGrxIBjD2knviVVeTZX+1dbmZq5zhnuvQVisnRqwkFxhSzTBTEiirBukh3o7vy05JS40atE15AjzH5I/BJfTkqbSnKJv/jLh0xrrz9psZ/A9RPxjM/8iuUfITQ3PhFjv8pTX4XA4/AIAAP//AwAiBvh48wMAAA==
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRTyW7bMBD9FWHOokJSFLXckthBjSB1kBht0RuXcUxEoQyKyoLA/15QdpCmt14IYsB585bhO3j1hNDB+X6/fEYfR8ghurnEKZeENoTTDW06yjsmi4aXrRD8N+TgrvENOqiFMcy0SEqUSISlFdHl1hBrsWWUWcorkTDVwwjdOyhXWHx2Both/IFhdIOHDn46b4eXNFu5wvTDZIsw9LjyY1TeJDKL5f31Zn1Lrmr5fXlxcXw54pgACmehA82YamwlCWOVJYIZTtq6LAmXrbZYS8VKe2xzPmLwqi9G+/jJwQ7RYzQdL3hZUMJbOORgVVSJtlYjbt72icls0yLV87k8X7t3eMYAHc8/DD3CnZnenT2NenK9PTueUY2PSek+DHsM0eHsyyy171V0g89Oky57hz5CDuv77LZXcTuEpy9m3R/1r/5D/iZNX76imSLay2HyEToQHHK4UWbnPGarBXQgmbCipQlIKyLqbUsUloroSrai0aWVmFK9HHx0fhqmMVv5iA9h5g8dXKl+xCPz82B2LqKJU0iifsnUeBsGO5mYfdrPaEGLkiYm6ynup5jdoXUBTcQkbxOmE94/LVxyShOVKQT0MbtVcZd9U+MuPbC1rQxHtKzUNdVbrBrbVI2prZSN3BpRGVqyyghhyq22rdK6LQ0XfKsF1hJywJR2Ni+YsZLVumakaSpORKORtLxGoqjirNZMtiLtxKeP2bpPfaq0tkGhSWNkS0RVSqJpQwkXFZXatJXF1PdhySl80UAO1xg89n9JvnEmDOOwjdlpC7IvJtxNPn3ebN6IF+fJ6+z2YjCPGLKUlnI+7ekpoMPhcPgDAAD//wMA36GF6gMEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRUy2rcMBT9FaP1yNHLsuxdmgcNIU1ohrZ0p8d1IuJIgySnDWH+vcgzpc2qdCPE9b1H555z8BsK+hnQiE53u4sXCCWjDSp+LTHCJCYKM7IlaiRspLJVlBCi1He0Qf4aXtGIemEttQNgDhKwcKTDhk8WOwcDJdQR1omKqR8yGt+Q9q2DF2+hjfkLpOxjQCP66oOLP+rb2rd2jotrU5zhKuSig61kzi/ur7e3d/iyl58uPnw4dGbIFaD1Do3IUKqV6ySmtHNYUMvw0HOOmRyMg15qyt1hzIcCKei5ze7pDwcXS4BiR9Yy3hLMBrTfIKeLrrSNzrB93VUmq0zntb5Zy+t1fEMvkNDINr8FPcCd2NmfPGez+NmdHM6i81Nez0nbEtMr2qBdijtIxcOq0WnO8Gzm163OT5eHnnrNFz/BLgXcWVxCQSPiEm3QqtE86+JjaI4Uz2YPoawfS/Ihe/svqIp0e9/czbpMMT2/s+T+oPLVf4h8o+2jD9BcnVdsKpwYSG03Got+GrAGrrHp5CCU4U5CTchZDMWHJS65uQoFHtK6EhrRpZ4zHPidJvvoC9iypLrnN1kH71J0iy3NHyspaUnLCatDS9ktpfkMziewBeoS27Qc8b68H2GSEVKpLClBKM2dLo/NR50fa4PrXWcZgKPc9MRM0CmnOmV7J6WSkxWdJZx2VgjLJ+MGbczALRNsMgL6KjDU5DRrWEnHeqGowsYMBAtKCB5Iz3FvFBAhmenNex2b27nOae6cAmGwsnLAouMSG6IIZqIj0tihc1Bz+VuSYx6EQht0DSnA/NfKN96mmONUmqPXzTsRPi+h/gia1fcfPuCfq9rn0T5Baqpb2oea+aNB+/1+/wsAAP//AwA/mN8hTwQAAA==
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSUzW7dNhCFX0XgWpT5L1K7JHZQ10htxEZTdEdyRrYQXeqCopwGxn33gvIN3HSXHTHgGZ75eMgXkvwByUDeHY9Xz5jKSlpSpr0kmDCUWSrYA7MDE4Owneq16nn/N2nJdIPfyUB6FSOPDqlEg1QB0zTIMVIAdJxxYEKr2tM/rmR4IX7qAJ+niN2y/ol5nZZEBvJlSrB8q2f7qYvzskGXlxmv01p8itXM5dX9zcPtHf3Ymz+u3r9/3bniWht0E5CBGBCSGeQUmBFUKbTUgkFqDSgWOdcC3KtsSgVz8nO3wtc3D7CUhCUOohOyY1Q4cmoJ+OKr7eBXfPh+rE52TJe13u7lfTm8kGfMZBDtD6Cv7S7iPF2U5TjjM85Hn1fMF3E5HHwC0pJjXo6Yy4Q7mn3aefZlWlJzPuzDPGEqpCW3983d7Mu45MNPvO5fEVz/AoFnzIEMRHoFQSFy1C4i98zz4EZtAhjQmhmwUTCFYuSgGQ+9l14xwdFIo9FCIC15nJfg59/XnZ8TLFhgvTACFTqhjHGRobQ46h4ZeGOCsdGBtL1QFqz0znvuAvbRmVhD8snHpylhc31Zp+EKlGNAFQ+eqn501KP0NGjjlA0SDFbNhyWVKW3LtjbXqeBj3vmRgXz084qv5N7l+DQVjGXLFepfpgrv8gJbLM1bAjjrWCeZqKKtHLfSfEaYMsaCFe9D3s79/icRRjBWrWw5YyrNnS9PzW9+faoboAcdBSJwGXoWRtQWrLaxB2OsGaPSkUmuo1JRjgGcD8HJKJQYg8LekJZgDVyzZ1yMVpjYR9rzqKnSY6ROiJ5G5ZkPzslRVSNvHJvbueq8BLCoArXROKq0NDQwy6hQmpkQnQascf6B5Bw+ZUlLbjAnnP8z8qcp5mVdxtKcU9j8BOHzlur/0eyJ/DYl+s9O+3KJXzE39bb8lOpTOV/QqSUH9OuW8bB/P8MLuavvpHnYfyHOVWeYasl98blsx3PZik5o6U6n0+lfAAAA//8DAFrkfDnDBAAA
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSUXU/dOBCG/0rk6zh1HNtxcteeA1qECghQt9o7xzMuVoN95Dh0EeK/r5xzaJfe9S4Zzcc7z7zJCwnmEclIPh4OZ08Y8kJqkv0W4owryjTl7J7pkfGRD83Ateql+IfUxF/iMxlJL6xt7YC0Q4VUAJN06pylADi0rAXGpSg9zbeFjC/E+AbwyVts4vIF0+JjICP52weIP8ps4xs7xxWaFGe8CEs2wRYx+7O7y/vrG3req6uzT5+OmQsupUHjgYxEAe+YwpYCU5wKgZpqUEi1AsFs20oOw7HMh4wpmLlZ4PsvDRBzwGxH3vCuYZQP5LUmYLIpsiez4P3zoSjZMO1LvN7C2+P4Qp4wkZHXb0CP7T7Y2X+w8fHRBEi4xHnNPoZ3kScEUpNDigdM2eNGaVt8nk1Jrk5zd7PHkElNru+qm9lkF9PjO3SnplfH+RLA9b3g6CahcEIG2DPX6W5iptWub1sjmXOqFziBYL2VAx80ain7fuhFQXV3xHvxB3RPGm6PiyUyks/eprhEl5t9zFeYm93sm90x7dzYHNPz2+vtT0DNjckPu9961eSzsQ8+YHWxL4paAWJgQEU7GSp6N1CDnaGTVIPQUwcKi/F2MWQf1rgu1UXI+C1tUMlIzs284BHnx2QffEab11TQfVWl8CZFWG2ufjmkZQ1rOsZL0ZoPa65uEXxCm7Eguk/rqd9vJVxxxoqUNSUMuSrLVX+Z5aEkQA/SckRou6lnk0OpQUtte1BKK2eFtKxrpRXCdm6CwUzT0FkuuJsE9orUBIshq+0bMI5jy6WjDpyjwihOtW0N5S1zApwUvHXvOFbX81bXAWgUE9VWDVTITtGJaUa5kExNdpCAxe5vSE6OFJrU5BJTwPl/K/88eHWyZvUOwu0ayv+l2lz1wwf670Z7H+13TFW5lvFhc87xQK+vr6//AQAA//8DAME6mqamBAAA
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSUUW/cKBSF/4rFs3EwYAx+a5tUm426GTWj7WrfLnCdoHrwCOPpVtH89xWeqbLdt76hK869h48DryTCAclA3h2PdyeMeSE1yWErccYVZZpytmd6YHwQrFFScsP136Qm4QG/k4H00rnWGaQCFVLpWUetGB31Hk3LWs94J0tPeF7I8EogNB5PwWEzL39iWsIcyUC+hOjnb2U2hMZN8+qbNE94H5cM0RUzt3dPD/vHHf3Yqz/u3r+/7FxwKQ2a4MlARj0q3VpO21GOVI5aU809o71BPhrhWc/1RRZixhRhahb/9c2Dn3PE7AbecNEwyg0518RDhmLbwoL778fiZMN0W+r1Vt6Wwys5YSIDr38AvbS7cVO4yfNxwhNOR0gLphs3Hw4QPanJMc1HTDnghmY77TRBDnOsrsM+TAFjJjV5fKp2E+RxToefeD1dENz/AoETJksG0ukORNsjSK/R+FF1yE0ndMtQShA99wzGUSrhvGJGjQjcO+lc33LujVCkJs/TbGH6fdn4Gc6sLjMUR4mGS6WMYyg0jl2PzINSVmlnvNA9l9prAQagNRZ7Z5QrIfkE7iVErO5vyUBUK700zFPZWqCyHw0FFEBtp4zUVniFRfNhjjnEdV6X6j5mfE4bPzKQjzAteCH3LrmXkNHlNRWof6ki3KXZry5XbwloWcMawXgRrfm45uoz+pDQZSx492m99vufhCvOWLGypoQxVzvIL9VvsLyUDb73neOIvhW2Z3bETnvdadd7pbQanewcE23npHRitN6AtUY4LvloJfaFMpbAVVvGpWHGcqepEYZRyTRQDb2hXScQmDFC+uL+jWP1OBUdCO81Sku1U4bKTihqmWaUy44p60znscT5B5Jr+GRJywOmiNN/jvwpuDQv85irawqrnyB8XmP5P6otkd9CpP9stG9n9xVTVW4LQixP5XpB55ocEJY14WH7foZXsivvpNpvv5BRjVBC1+QpQ8rr8VpuedvwlrXn8/n8LwAAAP//AwAW3FooxAQAAA==
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACoyTT2/bOBDFv4rAs6hQFEVRujVxgg3S1kHt3S72xj8jh4hCGiSVNgj83QvKTlu3PezNoEdvfvPmzSty8gnQgN7t99fP4FJEJUp2eaKEckwEpmRLxEDo0JBKNIxxIf5DJbJ38IIG1DGta90DboADZoa0WDWjxsZAX5PaENqyrCl3EQ2vSNrKwLPVUPn4D4RovUMD+myd8V9yb2krPfnZVMFPcOtikk5nmNX15m67vsc3Hf94fXl5rIwQs0BlDRrQKEYuakVxPbIRs1EILKghuOuBjn1jSEfF8TPrEgQnpyqaxx8MxicHSQ+0ok1FMO3RoURGJpmxlYywfdlnksWmVX4vl+fl5/CKniGggZZvhh7lLvRkL56imu1kLia/21m3u/JutLs5yJQbl2gf/B5CsrAYtN4UP5hqUpGKckoIKtEHqR+sg+J2VaynPLFsjBHAFBaa95i1DceKCIIpawlXum8NZMg7CA6mn1Q/WB189GMqTr4XZ32uvEvWzX6Oxa1LsDuBDuhGThFywRwCuFTcy/RQ/CXjQyY1nWk1BTB1ozqiRmiFEa3QneFc8FGzVpOmbjVjuhmV6aVSfaMpo6Ni0HFUoi2EJ+vk9N7vdtnL7/3O/1jBKOcpbfwclmRE84hKdGmdDC/Hir8jmFPVx+My3pSWQE3TMlBx2ufVZMGlM3/RgHjNDOuJwaxWErNu7LGERmLV8p4J1RgOOdb3wZtZp19X1hCKSvRpdvmUitu8rC/W4a+c/YL6ExvkXBVLlNu6q7VmFEtGCWaUSNwzSjEXtRTQEMlUjvLK60cIRd6XtO5MbL0p3gX9YBPoNIc85r9L7/WmuJ9kGn14Oju79Zz2cyo+gbEBdIJMsQ1zlrqxE/wG+zb3yUOWcTbHa1ym/Z/HeOVd9H+Q/+PGc+Ln5NHhcDh8AwAA//8DAKH1mMy4BAAA
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSUS2/dNhCF/4rAtSjz/dAuiR3UMFIbsZEW3VHkMCaiS11QlNPAuP+9oO4NUnfXnTDgGZ355pCvKLsDoBG9Ox5vXiDXFfWopr3ECFOYGMzIEzEjYSMngyaMc0n+Qj1Kd/ADjUgL76m3gDkowCIQiScePQ4BLCU0ECZF6+m+rmh8RS4NAV6Sh2FZv0BZ05LRiP5IOSzf279dGvy8bGEoywy3ea0u+2bm+ubx7un+AX/U6veb9+/PJ1dYW4MhBTSiaKIydGKYRhGxiMZgwwLB2gKLlgeimTnLUq5QspuHNXz75SEsNUP1IxsYHwhmFp16FFx1zfbkVnj6cWxOdkzXrd7v5f1zfEUvUNDI+p9Az+2u/Jyu1m2a4QXmoysrlCu/HA4uB9SjY1mOUGqCHc0LlGlZU21UvdfOGEqDcVpIHQyXjOvACQRDtAw2WKeEisxLGcNkrBZRBEZFUCDEpFGPdnjz7Gpacnfx/mFOkCvq0f1j9zC7GpdyeIP/8Uz09n8AbbbRiKSRjlMNTgQDNkQlgVnJDSUghOOaBeJiFIr7oIhVERwLXnivKWPBcoV69Mn555Shu71GI1JUBGFJwIJODgsdLXbAHZ6kssJMvA2KevRhyTXlbdnW7jZX+Fr2edGIPrp5hfOk74p/ThV83UqD8KdqwoeyhM3X7lcAKBnIwAlroq0et9p9hpAK+AoNx1PZLv3+I2GKEdKsbKVArt2Dq8/db259bgeCDtIzgED5pMkUQZpgpPE6KGVU9EJ6wqn0Qngep2DdNFnumWBxEqAbFWh5684Rt0IyFSV2QAUWlig8Ea8x8UIpb8ATbt9w7O7npnM8BANiwsYri4XkTWcIZkISNXkrA7Q0/0RyCYto272DkmH+18ifki/LusTaXVLTvYHwecvt+ej2BH1PGf+9075e/DcoXduWS7ndlMuCTj06gFu3Aof99Rlf0UO7Jt3T/ghZNXDFTY8eqyt1O17KlNGBUUJPp9PpHwAAAP//AwACiQ5HwwQAAA==
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRTS0/jMBD+K5HPdfArjpMb0KKtEEsF1e5qb35MqEVwKsfhIdT/vnJaxLK3vVjRxDPzvfyOgn4C1KLz/X71DCGNaIGSn0uMMImJwoxsiWoJazkt65qwmtHfaIH8NbyhFtXCWmobwBwkYOFIhQ3vLHYOGkqoI6wSeaZ+GFH7jrQvHTx7C+Uw/oA4+iGgFv30wQ0vebf2pe2HyZVx6GEdxqSDzWCWq/vr7e0GX9Xy++ri4nhzhDEPKL1DLepUJxU1DNNOdFh0SmHFHMF1A6xruCM1U8c2HxLEoPtydI+fGNyQAiTbspLxkmDWoMMCOZ10hm30CNu3fUYyy7TM9cVcnj/bd/QMEbVs8SHocdyZ7f3Z02gm37uz45n0+JiZ7uOwh5g8zLrMVPteJz+E4rTpsvcQElqg2/ti0+vUDfHpi1j3R/7r/6C/zdtXr2CnBO5ymEJCLco/brTd+QDFeolaJKlwoiEOC2o0FnXXYA1cY1PJRijDnYRs6uUQkg/TMI3FOiR4iDN81KIr3Y9wBH4e7c4nsGmKmdMvmRs3cXCTTcWn+pSUpOSE5aYp7adU3IHzEWyCzG4bp9O8f1qYZIRkKFOMEFKx0WlXfNPjLl9wtassA3CUm5qYDirlVKVs7aRUsrOisoTTygpheWdco41puGWCdUZALdECQTa7mPPlKmC04h2GmtdYOMqx0VWHK9m4ChSlBugXHYvbPvdp7pwCYbCyssGi4hIboghmoiLS2KZykKP0IcnJe5E9uYYYoP+L8o23cRiHLhWnEBRfRLibQn67xRyIFx/w66z2crCPEIvslvYhx/Rk0OFwOPwBAAD//wMAz5D+vAIEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRV227cNhD9FYGvlRTeJFEC8uCs16kR+ALvoin6xsvQy1omFyTl1DX23wtp7WadoA990WXImTlz5gz5grx8BDSgs/1+/QQ+J1Si7BYTxbStsKgo3mIxYDowUncC44azP1CJ3Bd4RgPquNZE91AxaKHiBjeVYlZXxkBPMDGYNnyOKe8TGl6QdLWBJ6ehDuk3iMkFjwb01XkTvs25pav1GCZTxzDCpU9Zej2DOV9vvmxvbquLrr1ef/p03JkgzQFqZ9CArLCtIIpWxHJbcStEJajBVdcDtT0zuKPi6OZ8hujlWCfz8B2DCdlD1gOtKatxRXt0KJGRWc6wlUywfd7PSBaazmd7uZiXz+EFPUFEAy3fCD2G+6BH9+ExqcmN5sPyRCXax7CHmB0sjCxFjqPMLvjiNcdqdOAzKtGn2WUzaQ0poQFdyDHBm3nt752Hiygf4VuID9fHvPX1eotKdBvDn6Dzrcw7NCBmtTBWaSJ5r6wC07e4kdBLyxUX1hhGtNWUWNx2naLcMmGUkm3bNUYpSlGJbjbF7SizDfHxXcM2xx5c/o8WbM5Way/VCObHkrYy3kNGA1KEWC26vueGNr1hILUATlplsBSCAQfDur63RDBGmSBWYCV62QisGuCGoRJdpk2W3sgxeFj/BXqaCUYD2sZpzncl9c55KC7P0YBawg3vsak4UbLine0rCUxWqml7LhQzLcwivpBunCKsZIb7EGf1X0+fYe7TKvjs/BSmVFz6DPdxaedJeTeb4izqncug8xTnRv3eziFvYzCTzsV3HRJc45rhhfMp76dc3IFxEXRe+HqFf7P50YW2FOMZyhQj+FzMrS9+lWnuPzGdaTQFMISpDisLjTCiEbozbStaq3mjMSON5lwzq0wvleqZppxaxaFrUYlgln2xTBontLWNtZViXVNxqk0lW6MrQbGGtmecA33HcHEzzn6SGSOAq0rotq94w9pKYYEryhvcKt03BuR7cZ+UKOq2JqRmDOP+hLfXgeGzrtYxhrgK03yKDad/l96G4qVYhce9GyEWH4uyuEpLns/gIcrx1LR+kuN0HMdT65uE3nlHud8thq1MD8vHxjzcQQrjE8S0GK4hb8xxbVFL8bGgZbG4r3agX1dkdk+wDWHUO+mOOVbBwJmX43Nyx0h38u9wBP91b5f3WdpfLxHL4ibvlsqKAyrRF4gexhOFXDkdQwo2F6+TW7zTzAnl5y7tR/n8E/O/sEY1PVOg3vYv6H8e5LvJzxdIsZwI35yv/lqEfh70A8RiHhTp/HxW/utxNY3ZbXcRpAFzFQz8GPRQokeQaYrwuFxRy6npIS4wzqfjsF36KzeOLoEO3iQ09O0Mm/NXtP+1jRAiaoKFOBwOh38AAAD//wMAez5l7Q8HAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSTTW/cIBCG/4rFeXEwYIx9S/OhRlGaqFm1VW98DA2KAyvASaNo/3uFd6s2vfWC0GhmeOd5hzcU1BOgCZ3udhfPEEpGG1T8GqKECkwkpmRL5EToxLp2EF0vB/YdbZC/hlc0oYEb05kRMAMBmFvSY82cwdbC2JHOEtrz2lP9yGh6Q8q3Fp69gTbmL5CyjwFN6KsPNr7Ut5VvzRwX26Y4w1XIRQVTxZxf3F9vb+/w5SA+XXz4cMjMkGuD1ls0ISedkJ2muHPcYe6kxJJagocRqBuZJQOVhzIfCqSg5jbbxz8abCwBiploS1lLMB3RfoOsKqrK1irD9nVXlayYzmt8s4bX6/SGniGhiW5+Az20OzGzP3nKevGzPTmcReXHvJ5OmRLTK9qgXYo7SMXDyug0Z3jS8+tW5cfLQ0695oufYJYC9iwuoaAJ1XFWRPOsio+hOSo8mz2Egjbo9r65m1VxMT29g3x/4Hb1H9hulHnwAZqrczQh0XHLR2Ix77TCfHAjVsAU1r0YudTMCqien8VQfFjikpurUOBHWlWiCV2qOcNB32kyD76AKUuq0r+JWniXol1Maf6Y05GWtIzQWrSU3VKaz2B9AlOgDrFNy7HfPyVUUEKqlCUlCKW5U+Wh+ajyQ02wg+0NBbAd0wPRDnppZS/NYIWQwhneG8K63nBumNN2VFqPzFBOneYwCLRBUHehWddPO6p6xwbcEWswF85g1VGCpVOiBys1Z8M7js3tXOsUs1YC11gaMWLeM4E1kQRT3hOhzdhbqJv2G8nRYl49uYYUYP5r5BtvUszRlebodfMOwucl1K/drL6/+IB/rrTPo3mE1FS3lA91i48G7ff7/S8AAAD//wMAGYtnLCEEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRTS2/cIBD+KxbnxQGMMfatTVI1itpESdRWvWFmyKI4sMI4D0X73yu8W7XprTc0mvnmewxvJJhHJAP5sNudP2HIM9mQ7NeSYEJRpqlgd0wPTAwNrzvNOeftT7Ih/hJfyUA6aS23PdIGFVIJrKVj4ywFwJ4zDky0smCa+5kMb8T4GvDJW6zj/A3T7GMgA/nuA8Tnstv42k5xgTrFCS/CnE2whczZ+e3l3dU1/dSpr+cfPx46Z5wLQO2BDMRppzQfBeVOOiqd1lQLYLTrUbi+AdYJfRjzIWMKZqpnePjDAWIOmO0gatHUjIqe7DcETDaF9mhmvHvdFSarTWelvlnL63N4I0+YyCA2vw09wJ3YyZ/Y+PhoApw4H/y8JRuyS3GHKXtcLVlVTpPJPobquOR08hgy2ZCr2+p6MtnF9PjOp9uD9Iv/UP7F2K0PWF2ckYEoLkH2DKjko6Gycz012Bg6tqqXemxAYYntNIbswxKXuboIGe/TypIM5JOZZjzw+5Ds1me0eUmF+g9VBvHF59MIpcDJhlynCIvN1R+7OatZ3TBRMJa8W3J1g+AT2oxF011ajvD/jAglGCvMlpQw5Ora5G312czb0gAdtFYgAm/Gjo0OWw261bYDpbRyVraWNby1UtrGjdCbcewbK6Rwo8ROFd4l3Wo9KN5oyXXHqbXgqIQeae9YSyU40K2UQoF7Z2t1NZU50wBolCPVVvVUto2iI9OMCtkyNdq+BSy389uSY+KyRHSJKeD0l+Qv3qY4R5erY/TVOxNullA+a7WewbMP9GU1/yzaB0xVCc/4UO7ymNd+v9//AgAA//8DAFu9oLHzAwAA
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSUTW/cNhCG/4rAsyhT/KZuSeyghpHaiBdp0Rs/hjERLbWgKKeBsf+9oLyBm956I4ac4TsPX84LyvYIaELvTqebZ8h1RT2qaQ9RQiUmGlNyIHoidGJ0oJwpQfhfqEfpDn6gCSnu/egNYAYSMA9EYMeixyGAGckYCBW81bRfVzS9IJuGAM/Jw7CsX6CsacloQn+kHJbv7W6bBj8vWxjKMsNtXqvNvom5vnm8O9w/4I9K/n7z/v3ryRXWVmBIAU0oaiV15Ap7KTTmnglseTRYK0lFZFYANa9pKVco2c7DGr69aQhLzVD9RAfKBoKpQeceBVttk+3sCocfp6Zkx3Td4v0e3pfTC3qGgiba/wT6Wu7Kz+lq3dwMzzCfbFmhXPnleLQ5oB6dynKCUhPsaJ6huGVNtVH1XlmtxzFoq7hQQTNBmQqMQNBEiWCCsZLLSL0QMThtFI880JEHCZw7hXq0w5tnW9OSu4v2D3OCXFGP7h+7h9nWuJTjL/gfX4ne/g+gTTaakNDCslGB5UGDCVG2bcH0SIBzyxQNxMbIJfNBEiMjWBo8916NlAbDJOrRJ+ufUobu9hpNSI48cEMC5qOzmKtosAVmsRPScO1YaxT16MOSa8rbsq3dba7wtez9ogl9tPMKr52+K/4pVfB1Kw3Cn7IlPpQlbL52bwYYyUAGRmhL2uppq91nCKmAr9BwHMp2qfefFCopIU3KVgrk2j3Y+tT9ZtendiCoIDwFCCNzirgIQgcttFdBSi2j58ITNgrPuWfRBWOdM8xTTqPjoBoVaH7rdosHDcyNRGNposXceIeNNA7T6AUnI2hhm63eOHb3c8uzLAQN3GHtpcFcMIkd0QRTLoh03ogAzc0/kVzMwjXq0R2UDPO/Wv6UfFnWJdbu4pruFwift9zGR7c76HvK+O+d9vXiv0Hp2mvZlNtPuTzQuUdHsOtW4LhPn+kFPbRv0h32ISTUIAjTPXqsttTtdAlLMQhB2Pl8Pv8DAAD//wMAUcbLucIEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpSUS2/cNhSF/4rAtShTfFO7JHZQ10g9iAdN0R0fVzYRDTWgqEkDY/57Qc0EqbvLTrjiuTz8eHhfUbIHQAN6dzzenSCVBbWoxK1ECZWYaEzJnuiB0IHRrpdaCS3/Ri2KD/AdDUhx73tvADOQgHkgAjs2ehwCmJ70gVDBa0/7vKDhFdnYBThFD928/Al5iXNCA/oSU5i/1b1t7Pw0r6HL8wT3aSk2+Wrm9u7pYf+4wx+V/OPu/fvLygWW2qCLAQ1o1ErqkSvspdCYeyaw5aPBWkkqRmYFUHORxVQgJzt1S/j600OYS4LiB9pR1hFMDTq3KNhiq21nF9h/P1YnG6bbWm+38vY5vKITZDTQ9gfQS7sbP8WbMh8nOMF0tHmBfOPnw8GmgFp0zPMRcomwodlOO022xDk1180+TBFSQS16fGp2ky3jnA9veD1dENz/AoETZIcGJLSwrFdgedBgwijrb8F0T4BzyxQNxI4jl8wHSYwcwdLgufeqpzQYJlGLnqfZ2en3ZeNnKHE6EEUlBQ6GcimNJ8A0jEIBCVZKJ7U3gWlFuQ6aWWNtbxwob6SvIflk/UtM0NzfogHJngduSMC8dxZzNRpsgVnshDRcOxYkVM2HOZWY1nldmvtU4Dlv/NCAPtppgQu5d9m/xAK+rLlC/UtW4S7PYfWl+ZmAnnSkY4RW0VqOa2k+Q4gZfIGKd5/Xa7//SaikhFQra86QSrOz5aX5zS4vdUFQQXgKEHrmFHEjCB200F4FKbUcPReesF54zj0bXTDWOcM85XR0HFSlDDVwzZZxanrDKCHYjJxibpzERjuFGVHeh970AtQbjs3jVHWWhaCBO6y9NJgLJrEjmmDKBZHOGxGgxvkHkmv4uEYteoCcYPrPkT9Fn+dlHktzTWHzBsLnNdX50WyJ/BYT/mejfTv7r5Cbels2pvpUrhd0btEB7LJmOGzjZ3hFu/pOmv02hYTqBGG6RU/F5rIer2UpOiEIO5/P538BAAD//wMARF4PZcMEAAA=
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRTy07cMBT9lcjrODi24zjZwQyoCFEQjNqqOz9uGItgjxyHh9D8e+XMIEp33VlXPsfncf2OvHoC1KPT3e78GXyaUImSW0aUUIGJxJRsiOwJ7Rmrmo4TIdrfqETuCt5Qj1puTG06wAwEYG5JgzUbDLYWuprUltCGZ071MKH+HSlXWXh2Bqow/YA4ueBRj346b8NLflu5yoxhtlUMI1z6KSlvspj1+f3V5uYWX7Ti+/nZ2eHmBFMmqJxFPRpkK+TAW2xEIzE3rMGKDx2WraDNwFQDtDvAnE8QvRqryT5+arAheUimpxVlFcG0Q/sSWZVUlq3VBJu3XVayxLTO83IZL8f+HT1DRD0tPwI90J2Y0Z2Y8PSkvD0ZnHfTFpVoF8MOYnKwRLK4HEeVXPDF8ZHV6MAnVKKb++J2VGkI8elLTvcH65f/4fxama3zUFyuUY9EzS3viMW81grzduiwAqawbkTHpWZWQK5tFXxyfg7zVFz6BA9xUYl6dKHGCQ76TqPZugQmzTFL/yUyEF5dWgWbBwSV6DYGO5tUfMZdk4pUjNDMMafdnIo7sC6CSZA9beJ8pP8HQgUlmXE1xwg+FbcqbYtvatrmC7a1jaEAtma6JXqARlrZSNNaIaQYDG8MYXVjODds0LZTWnfMUE4HzaEVWXdut1gWCqxqKa8VZtBpzBlrsWZCYU25YhIoJZB34DPW4mbMOMWslcA1lkZ0mDdMYE0kwZQ3RGjTNXbBfURybJxLVKIriB7GvyxfOxPDFIZUHKsvvoRwN/v8WYtlDV6cx69L+OtgHiEWuTzlfN7LY1/7/X7/BwAA//8DAEtP7wnzAwAA
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
https://dc.services.visualstudio.com/v2/track
|
||||
Content-Type:application/x-json-stream
|
||||
Content-Encoding:gzip
|
||||
|
||||
H4sIAAAAAAAACpRTTW/cIBD9KxZn42DAGPvWZlM1itpEzaqtesPMOIvihRXGaato/3uFd6M0vfWGRrzH+xieiTd7JD15dzhcPaFPMylJcuuIM64o05SzLdM9470QVdsIxYT+QUribvA36Ukrra1th1SgQiqBNXQQo6UA2NWsBsYbmTnNw0z6Z2JcBfjkLFZh/opxdsGTnnxzHsLP/LZxlZ3CAlUME177ORlvs5jN1f3N9vaOfmjV56v37083Z5wzQeWA9EQBF0xhTYEpTqVETTUopFqBZLauGw7dCeZ8wujNVM3w+KoBQvKYbM8rLipGeUeOJQGTTJY9mBm3vw9ZyRrTJs/Ldbwe+2fyhJH0vHwJ9ER3YSd3YcN+bzxcjM67eUdKcojhgDE5XCNZXU6TSS744vzI5eTQJ1KS2/vibjJpDHH/Jqf7k/Xr/3D+ydid81hcbzKmliA7BlTWg6GyHTtqUBg6NKqTehCgMNd2GXxyfgnLXFz7hA9xVUl68sFMM570vYt25xLatMQs/bvKQPzl0mWAPKhJSe5igMWm4jXumlWsEoxnjiUdllR8QXARbcLsaRuXM/0/EK44Y1nZEiP6VNyZtCs+mnmXL0ALjeWIUIuhZcOIjQbdaNuCUlqNVjaWibqxUloxDtCZYeiE5ZKPg8RWZd253WJdKItqHBvZ0tpoSSWIjupOaQq1sFZzrqXJQl5jLW6njDMCQKMcqLaqo7IRig5MM8plw9RguwYw785LJOfGpSYlucHocfrL8idnY5jDmIpz9cWbEL4sPn/WYl2Dn87TX2v4m2AfMRa5PON83stzX8fj8fgHAAD//wMAJODDNvMDAAA=
|
||||
@@ -30,6 +30,17 @@ public class AppDBContext(DbContextOptions<AppDBContext> options) : DbContext(op
|
||||
public DbSet<StockBalance> StockBalances { get; set; }
|
||||
public DbSet<StockMovement> StockMovements { get; set; }
|
||||
public DbSet<StoreKycDocument> StoreKycDocuments { get; set; }
|
||||
public DbSet<PriceList> PriceLists { get; set; }
|
||||
public DbSet<PriceListItem> PriceListItems { get; set; }
|
||||
public DbSet<Supplier> Suppliers { get; set; }
|
||||
public DbSet<DriverProfile> DriverProfiles { get; set; }
|
||||
public DbSet<DriverComplianceConfig> DriverComplianceConfigs { get; set; }
|
||||
public DbSet<RideCancelRequest> RideCancelRequests { get; set; }
|
||||
public DbSet<Scheme> Schemes { get; set; }
|
||||
public DbSet<SchemeRedemption> SchemeRedemptions { get; set; }
|
||||
public DbSet<SchemeBundleComponent> SchemeBundleComponents { get; set; }
|
||||
public DbSet<LoadingSheet> LoadingSheets { get; set; }
|
||||
public DbSet<LoadingSheetItem> LoadingSheetItems { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -58,6 +69,97 @@ public class AppDBContext(DbContextOptions<AppDBContext> options) : DbContext(op
|
||||
.HasIndex(sb => new { sb.FK_ItemId, sb.LocationId })
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<PriceListItem>()
|
||||
.HasIndex(pli => new { pli.FK_PriceListId, pli.FK_ItemId })
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<DriverProfile>()
|
||||
.HasIndex(dp => dp.FK_UserId)
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<Vehicle>()
|
||||
.HasOne<Warehouse>()
|
||||
.WithMany()
|
||||
.HasForeignKey(nameof(Vehicle.DefaultWarehouseId))
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired(false);
|
||||
|
||||
modelBuilder.Entity<DeliveryRun>()
|
||||
.HasOne(r => r.SourceWarehouse)
|
||||
.WithMany()
|
||||
.HasForeignKey(r => r.FK_SourceWarehouseId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<DeliveryRun>()
|
||||
.HasOne(r => r.DriverProfile)
|
||||
.WithMany()
|
||||
.HasForeignKey(r => r.FK_DriverProfileId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<SchemeRedemption>()
|
||||
.HasOne(r => r.Scheme)
|
||||
.WithMany(s => s.Redemptions)
|
||||
.HasForeignKey(r => r.FK_SchemeId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<SchemeRedemption>()
|
||||
.HasOne(r => r.Order)
|
||||
.WithMany()
|
||||
.HasForeignKey(r => r.FK_OrderId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<SchemeRedemption>()
|
||||
.HasOne(r => r.FreeItem)
|
||||
.WithMany()
|
||||
.HasForeignKey(r => r.FK_FreeItemId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<Scheme>()
|
||||
.HasOne(s => s.TriggerItem)
|
||||
.WithMany()
|
||||
.HasForeignKey(s => s.FK_TriggerItemId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<Scheme>()
|
||||
.HasOne(s => s.FreeItem)
|
||||
.WithMany()
|
||||
.HasForeignKey(s => s.FK_FreeItemId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<SchemeBundleComponent>()
|
||||
.HasOne(c => c.Scheme)
|
||||
.WithMany(s => s.BundleComponents)
|
||||
.HasForeignKey(c => c.FK_SchemeId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
modelBuilder.Entity<SchemeBundleComponent>()
|
||||
.HasOne(c => c.Item)
|
||||
.WithMany()
|
||||
.HasForeignKey(c => c.FK_ItemId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<SchemeBundleComponent>()
|
||||
.HasIndex(c => new { c.FK_SchemeId, c.FK_ItemId })
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<LoadingSheet>()
|
||||
.HasOne(s => s.SourceWarehouse)
|
||||
.WithMany()
|
||||
.HasForeignKey(s => s.FK_SourceWarehouseId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<LoadingSheet>()
|
||||
.HasOne(s => s.Ride)
|
||||
.WithMany()
|
||||
.HasForeignKey(s => s.FK_RideId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<LoadingSheetItem>()
|
||||
.HasOne(i => i.Item)
|
||||
.WithMany()
|
||||
.HasForeignKey(i => i.FK_ItemId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
Seed.RoleAndPermissionSeed.Apply(modelBuilder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,65 +14,6 @@ public static class RoleAndPermissionSeed
|
||||
private static readonly Guid RegionalManagerId = new("10000000-0000-0000-0000-000000000005");
|
||||
private static readonly Guid RegionalAgencyId = new("10000000-0000-0000-0000-000000000006");
|
||||
|
||||
private static readonly (string Code, string Description) [] PermissionDefs =
|
||||
[
|
||||
("regions.view", "View regions"),
|
||||
("regions.create", "Create regions"),
|
||||
("regions.update", "Update regions"),
|
||||
("regions.delete", "Delete regions"),
|
||||
|
||||
("routes.view", "View routes"),
|
||||
("routes.create", "Create routes"),
|
||||
("routes.update", "Update routes"),
|
||||
("routes.delete", "Delete routes"),
|
||||
|
||||
("vehicles.view", "View vehicles"),
|
||||
("vehicles.create", "Create vehicles"),
|
||||
("vehicles.update", "Update vehicles"),
|
||||
("vehicles.delete", "Delete vehicles"),
|
||||
|
||||
("stores.view", "View stores"),
|
||||
("stores.create", "Create stores"),
|
||||
("stores.update", "Update stores"),
|
||||
("stores.delete", "Delete stores"),
|
||||
("stores.kyc.verify", "Verify or reject store KYC documents"),
|
||||
("stores.credit.update", "Update store credit limit and outstanding balance"),
|
||||
|
||||
("warehouses.view", "View warehouses"),
|
||||
("warehouses.create", "Create warehouses"),
|
||||
("warehouses.update", "Update warehouses"),
|
||||
("warehouses.delete", "Delete warehouses"),
|
||||
|
||||
("orders.view", "View orders"),
|
||||
("orders.create", "Create orders"),
|
||||
("orders.update", "Update orders"),
|
||||
("orders.delete", "Delete orders"),
|
||||
|
||||
("users.view", "View users"),
|
||||
("users.create", "Create users"),
|
||||
("users.update", "Update users"),
|
||||
("users.deactivate", "Deactivate users"),
|
||||
("users.assign_role", "Assign a role to a user"),
|
||||
("users.assign_scope", "Assign region/route/store scope to a user"),
|
||||
|
||||
("items.view", "View items, brands and UOMs"),
|
||||
("items.create", "Create items, brands and UOMs"),
|
||||
("items.update", "Update items, brands and UOMs"),
|
||||
("items.delete", "Delete items, brands and UOMs"),
|
||||
|
||||
("categories.view", "View categories"),
|
||||
("categories.create", "Create categories and subcategories"),
|
||||
("categories.update", "Update categories and subcategories"),
|
||||
("categories.delete", "Delete categories and subcategories"),
|
||||
];
|
||||
|
||||
private static readonly Dictionary<string, Guid> PermissionIds = PermissionDefs
|
||||
.Select((p, i) => (p.Code, Id: DeterministicPermissionId(i)))
|
||||
.ToDictionary(x => x.Code, x => x.Id);
|
||||
|
||||
private static Guid DeterministicPermissionId(int index) =>
|
||||
new($"20000000-0000-0000-0000-{index + 1:D12}");
|
||||
|
||||
public static void Apply(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Role>().HasData(
|
||||
@@ -83,66 +24,5 @@ public static class RoleAndPermissionSeed
|
||||
new Role { Id = RegionalManagerId, Name = "RegionalManager", Level = 50, CreatedAt = SeedDate, IsActive = true },
|
||||
new Role { Id = RegionalAgencyId, Name = "RegionalAgency", Level = 60, CreatedAt = SeedDate, IsActive = true }
|
||||
);
|
||||
|
||||
modelBuilder.Entity<Permission>().HasData(
|
||||
PermissionDefs.Select(p => new Permission
|
||||
{
|
||||
Id = PermissionIds[p.Code],
|
||||
Code = p.Code,
|
||||
Description = p.Description,
|
||||
CreatedAt = SeedDate,
|
||||
IsActive = true
|
||||
})
|
||||
);
|
||||
|
||||
var itemViewPerms = new[] { "items.view", "categories.view" };
|
||||
var itemManagePerms = new[] { "items.view", "items.create", "items.update", "categories.view" };
|
||||
var itemPerms = new[] { "items.view", "items.create", "items.update", "items.delete", "categories.view", "categories.create", "categories.update", "categories.delete" };
|
||||
|
||||
var salesRepPerms = new[] { "orders.view", "orders.create", "orders.update", "stores.view", "routes.view" }.Concat(itemViewPerms).ToArray();
|
||||
var supervisorPerms = salesRepPerms.Concat(["orders.delete", "stores.create", "stores.update", "stores.credit.update"]).ToArray();
|
||||
var areaManagerPerms = supervisorPerms.Concat(["vehicles.view", "warehouses.view", "stores.kyc.verify"]).Concat(itemManagePerms).Distinct().ToArray();
|
||||
var areaSupervisorPerms = areaManagerPerms.Concat(["routes.create", "routes.update", "stores.delete"]).Concat(itemPerms).Distinct().ToArray();
|
||||
|
||||
var regionalManagerPerms = new[]
|
||||
{
|
||||
"orders.view", "orders.create", "orders.update", "orders.delete",
|
||||
"stores.view", "stores.create", "stores.update", "stores.delete", "stores.kyc.verify", "stores.credit.update",
|
||||
"routes.view", "routes.create", "routes.update", "routes.delete",
|
||||
"vehicles.view", "vehicles.create", "vehicles.update", "vehicles.delete",
|
||||
"warehouses.view", "warehouses.create", "warehouses.update", "warehouses.delete",
|
||||
"regions.view", "users.view",
|
||||
"items.view", "items.create", "items.update", "items.delete",
|
||||
"categories.view", "categories.create", "categories.update", "categories.delete"
|
||||
};
|
||||
var regionalAgencyPerms = PermissionDefs.Select(p => p.Code).ToArray();
|
||||
|
||||
var rolePermissionMap = new (Guid RoleId, string[] Codes)[]
|
||||
{
|
||||
(SalesRepId, salesRepPerms),
|
||||
(SupervisorId, supervisorPerms),
|
||||
(AreaManagerId, areaManagerPerms),
|
||||
(AreaSupervisorId, areaSupervisorPerms),
|
||||
(RegionalManagerId, regionalManagerPerms),
|
||||
(RegionalAgencyId, regionalAgencyPerms),
|
||||
};
|
||||
|
||||
modelBuilder.Entity<RolePermission>().HasData(
|
||||
rolePermissionMap.SelectMany(rp => rp.Codes.Select(code => new RolePermission
|
||||
{
|
||||
Id = DeterministicRolePermissionId(rp.RoleId, PermissionIds[code]),
|
||||
FK_RoleId = rp.RoleId,
|
||||
FK_PermissionId = PermissionIds[code],
|
||||
CreatedAt = SeedDate,
|
||||
IsActive = true
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
private static Guid DeterministicRolePermissionId(Guid roleId, Guid permissionId)
|
||||
{
|
||||
using var md5 = System.Security.Cryptography.MD5.Create();
|
||||
var bytes = md5.ComputeHash(roleId.ToByteArray().Concat(permissionId.ToByteArray()).ToArray());
|
||||
return new Guid(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.DriverComplianceConfig;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/driver-compliance-config")]
|
||||
[Authorize]
|
||||
public class DriverComplianceConfigController(DriverComplianceConfigService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "compliance.manage")]
|
||||
public async Task<IActionResult> Get()
|
||||
{
|
||||
var result = await service.GetAsync();
|
||||
return result is null ? NoContent() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
[Authorize(Policy = "compliance.manage")]
|
||||
public async Task<IActionResult> Upsert(UpdateDriverComplianceConfigRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
var result = await service.UpsertAsync(request, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Distribution.Features.DriverComplianceConfig;
|
||||
|
||||
public record DriverComplianceConfigResponse(
|
||||
Guid Id,
|
||||
bool EnforceLicenseExpiry,
|
||||
bool EnforceMedicalClearance,
|
||||
DateTime UpdatedAt,
|
||||
Guid UpdatedBy);
|
||||
|
||||
public record UpdateDriverComplianceConfigRequest(
|
||||
bool EnforceLicenseExpiry,
|
||||
bool EnforceMedicalClearance);
|
||||
@@ -0,0 +1,16 @@
|
||||
using Distribution.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.DriverComplianceConfig;
|
||||
|
||||
public class DriverComplianceConfigRepository(AppDBContext context) : IDriverComplianceConfigRepository
|
||||
{
|
||||
public async Task<Models.DriverComplianceConfig?> GetAsync() =>
|
||||
await context.DriverComplianceConfigs.FirstOrDefaultAsync();
|
||||
|
||||
public async Task AddAsync(Models.DriverComplianceConfig config) =>
|
||||
await context.DriverComplianceConfigs.AddAsync(config);
|
||||
|
||||
public void Update(Models.DriverComplianceConfig config) =>
|
||||
context.DriverComplianceConfigs.Update(config);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.DriverComplianceConfig;
|
||||
|
||||
public class DriverComplianceConfigService(IDriverComplianceConfigRepository repo, IUnitOfWork uow)
|
||||
{
|
||||
public async Task<DriverComplianceConfigResponse?> GetAsync()
|
||||
{
|
||||
var config = await repo.GetAsync();
|
||||
return config is null
|
||||
? null
|
||||
: new DriverComplianceConfigResponse(
|
||||
config.Id,
|
||||
config.EnforceLicenseExpiry,
|
||||
config.EnforceMedicalClearance,
|
||||
config.UpdatedAt,
|
||||
config.UpdatedBy);
|
||||
}
|
||||
|
||||
public async Task<DriverComplianceConfigResponse> UpsertAsync(UpdateDriverComplianceConfigRequest request, Guid updatedBy, CancellationToken ct = default)
|
||||
{
|
||||
var config = await repo.GetAsync();
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (config is null)
|
||||
{
|
||||
config = new global::Distribution.Models.DriverComplianceConfig
|
||||
{
|
||||
EnforceLicenseExpiry = request.EnforceLicenseExpiry,
|
||||
EnforceMedicalClearance = request.EnforceMedicalClearance,
|
||||
UpdatedBy = updatedBy,
|
||||
UpdatedAt = DateTime.Now
|
||||
};
|
||||
await repo.AddAsync(config);
|
||||
}
|
||||
else
|
||||
{
|
||||
config.EnforceLicenseExpiry = request.EnforceLicenseExpiry;
|
||||
config.EnforceMedicalClearance = request.EnforceMedicalClearance;
|
||||
config.UpdatedBy = updatedBy;
|
||||
config.UpdatedAt = DateTime.Now;
|
||||
repo.Update(config);
|
||||
}
|
||||
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
|
||||
return new DriverComplianceConfigResponse(
|
||||
config.Id,
|
||||
config.EnforceLicenseExpiry,
|
||||
config.EnforceMedicalClearance,
|
||||
config.UpdatedAt,
|
||||
config.UpdatedBy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Distribution.Features.DriverComplianceConfig;
|
||||
|
||||
public interface IDriverComplianceConfigRepository
|
||||
{
|
||||
Task<Models.DriverComplianceConfig?> GetAsync();
|
||||
Task AddAsync(Models.DriverComplianceConfig config);
|
||||
void Update(Models.DriverComplianceConfig config);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/driver-profiles")]
|
||||
[Authorize]
|
||||
public class DriverProfileController(DriverProfileService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "driver_profiles.view")]
|
||||
public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "driver_profiles.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "driver_profiles.create")]
|
||||
public async Task<IActionResult> Create(CreateDriverProfileRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "driver_profiles.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateDriverProfileRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "driver_profiles.deactivate")]
|
||||
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
|
||||
{
|
||||
var success = await service.DeactivateAsync(id, ct);
|
||||
return success ? NoContent() : NotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
public record DriverProfileResponse(
|
||||
Guid Id,
|
||||
Guid UserId,
|
||||
string UserFullName,
|
||||
string LicenseNumber,
|
||||
DateTime LicenseExpiry,
|
||||
DateTime MedicalClearanceExpiry,
|
||||
bool IsActive,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateDriverProfileRequest(
|
||||
Guid FK_UserId,
|
||||
string LicenseNumber,
|
||||
DateTime LicenseExpiry,
|
||||
DateTime MedicalClearanceExpiry);
|
||||
|
||||
public record UpdateDriverProfileRequest(
|
||||
string LicenseNumber,
|
||||
DateTime LicenseExpiry,
|
||||
DateTime MedicalClearanceExpiry);
|
||||
@@ -0,0 +1,40 @@
|
||||
using Distribution.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
public class DriverProfileRepository(AppDBContext context) : IDriverProfileRepository
|
||||
{
|
||||
public async Task<global::Distribution.Models.DriverProfile?> GetByIdAsync(Guid id) =>
|
||||
await context.DriverProfiles
|
||||
.Include(p => p.User)
|
||||
.FirstOrDefaultAsync(p => p.Id == id);
|
||||
|
||||
public async Task<global::Distribution.Models.DriverProfile?> GetByUserIdAsync(Guid userId) =>
|
||||
await context.DriverProfiles
|
||||
.Include(p => p.User)
|
||||
.FirstOrDefaultAsync(p => p.FK_UserId == userId);
|
||||
|
||||
public async Task<List<global::Distribution.Models.DriverProfile>> GetAllAsync(int page, int pageSize) =>
|
||||
await context.DriverProfiles
|
||||
.Include(p => p.User)
|
||||
.Where(p => p.IsActive)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync() =>
|
||||
await context.DriverProfiles.CountAsync(p => p.IsActive);
|
||||
|
||||
public async Task AddAsync(global::Distribution.Models.DriverProfile profile) =>
|
||||
await context.DriverProfiles.AddAsync(profile);
|
||||
|
||||
public void Update(global::Distribution.Models.DriverProfile profile) =>
|
||||
context.DriverProfiles.Update(profile);
|
||||
|
||||
public void Deactivate(global::Distribution.Models.DriverProfile profile)
|
||||
{
|
||||
profile.IsActive = false;
|
||||
context.DriverProfiles.Update(profile);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
public class DriverProfileService(IDriverProfileRepository repo, IUnitOfWork uow)
|
||||
{
|
||||
public async Task<PagedResponse<DriverProfileResponse>> GetAllAsync(int page, int pageSize)
|
||||
{
|
||||
var total = await repo.GetCountAsync();
|
||||
var items = await repo.GetAllAsync(page, pageSize);
|
||||
return new PagedResponse<DriverProfileResponse>(page, pageSize, total,
|
||||
items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<DriverProfileResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var profile = await repo.GetByIdAsync(id);
|
||||
return profile is null || !profile.IsActive ? null : ToResponse(profile);
|
||||
}
|
||||
|
||||
public async Task<DriverProfileResponse> CreateAsync(CreateDriverProfileRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var existing = await repo.GetByUserIdAsync(request.FK_UserId);
|
||||
if (existing is not null && existing.IsActive)
|
||||
throw new InvalidOperationException("An active driver profile already exists for this user");
|
||||
|
||||
var profile = new global::Distribution.Models.DriverProfile
|
||||
{
|
||||
FK_UserId = request.FK_UserId,
|
||||
LicenseNumber = request.LicenseNumber,
|
||||
LicenseExpiry = request.LicenseExpiry,
|
||||
MedicalClearanceExpiry = request.MedicalClearanceExpiry
|
||||
};
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.AddAsync(profile);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
|
||||
var saved = await repo.GetByIdAsync(profile.Id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<DriverProfileResponse?> UpdateAsync(Guid id, UpdateDriverProfileRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var profile = await repo.GetByIdAsync(id);
|
||||
if (profile is null || !profile.IsActive) return null;
|
||||
|
||||
profile.LicenseNumber = request.LicenseNumber;
|
||||
profile.LicenseExpiry = request.LicenseExpiry;
|
||||
profile.MedicalClearanceExpiry = request.MedicalClearanceExpiry;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
repo.Update(profile);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
|
||||
return ToResponse(profile);
|
||||
}
|
||||
|
||||
public async Task<bool> DeactivateAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var profile = await repo.GetByIdAsync(id);
|
||||
if (profile is null || !profile.IsActive) return false;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
repo.Deactivate(profile);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static DriverProfileResponse ToResponse(global::Distribution.Models.DriverProfile p) =>
|
||||
new(p.Id, p.FK_UserId, p.User?.FullName ?? string.Empty,
|
||||
p.LicenseNumber, p.LicenseExpiry, p.MedicalClearanceExpiry,
|
||||
p.IsActive, p.CreatedAt);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
public interface IDriverProfileRepository
|
||||
{
|
||||
Task<global::Distribution.Models.DriverProfile?> GetByIdAsync(Guid id);
|
||||
Task<global::Distribution.Models.DriverProfile?> GetByUserIdAsync(Guid userId);
|
||||
Task<List<global::Distribution.Models.DriverProfile>> GetAllAsync(int page, int pageSize);
|
||||
Task<int> GetCountAsync();
|
||||
Task AddAsync(global::Distribution.Models.DriverProfile profile);
|
||||
void Update(global::Distribution.Models.DriverProfile profile);
|
||||
void Deactivate(global::Distribution.Models.DriverProfile profile);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ namespace Distribution.Features.Item;
|
||||
public interface IItemRepository
|
||||
{
|
||||
Task<Models.Item?> GetByIdAsync(Guid id);
|
||||
Task<Models.Item?> GetBySkuAsync(string sku);
|
||||
Task<List<Models.Item>> GetAllAsync(Guid? categoryId = null, Guid? subCategoryId = null, Guid? brandId = null);
|
||||
Task<bool> SkuExistsAsync(string sku, Guid? excludeId = null);
|
||||
Task<Models.Item?> GetByExternalErpItemIdAsync(int erpId);
|
||||
|
||||
@@ -15,6 +15,9 @@ public class ItemRepository(AppDBContext context) : IItemRepository
|
||||
.Include(i => i.Conversions).ThenInclude(c => c.ToUom)
|
||||
.FirstOrDefaultAsync(i => i.Id == id);
|
||||
|
||||
public async Task<Models.Item?> GetBySkuAsync(string sku) =>
|
||||
await context.Items.FirstOrDefaultAsync(i => i.Sku == sku && i.IsActive);
|
||||
|
||||
public async Task<List<Models.Item>> GetAllAsync(Guid? categoryId = null, Guid? subCategoryId = null, Guid? brandId = null)
|
||||
{
|
||||
var query = context.Items
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.LoadingEvent;
|
||||
|
||||
public interface ILoadingSheetRepository
|
||||
{
|
||||
Task<LoadingSheet?> GetByIdAsync(Guid id);
|
||||
Task<LoadingSheet?> GetActiveByRideIdAsync(Guid rideId);
|
||||
Task<List<LoadingSheet>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? rideId, LoadingSheetStatus? status);
|
||||
Task<List<(Guid ItemId, decimal TotalQty)>> GetAggregatedOrderItemsByRouteIdAsync(Guid routeId);
|
||||
Task AddAsync(LoadingSheet sheet);
|
||||
void Update(LoadingSheet sheet);
|
||||
void RemoveItems(IEnumerable<LoadingSheetItem> items);
|
||||
Task AddItemsAsync(IEnumerable<LoadingSheetItem> items);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using Distribution.Models;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.LoadingEvent;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/loading-sheets")]
|
||||
[Authorize]
|
||||
public class LoadingSheetController(LoadingSheetService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "loading.view")]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? rideId,
|
||||
[FromQuery] LoadingSheetStatus? status,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(rideId, status, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "loading.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "loading.dispatch")]
|
||||
public async Task<IActionResult> Create(CreateLoadingSheetRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/items")]
|
||||
[Authorize(Policy = "loading.dispatch")]
|
||||
public async Task<IActionResult> SetItems(Guid id, SetItemsRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.SetItemsAsync(id, request, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/confirm-dispatch")]
|
||||
[Authorize(Policy = "loading.dispatch")]
|
||||
public async Task<IActionResult> ConfirmDispatch(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ConfirmDispatchAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/receipt-items")]
|
||||
[Authorize(Policy = "loading.receive")]
|
||||
public async Task<IActionResult> SetReceiptItems(Guid id, SetReceiptItemsRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.SetReceiptItemsAsync(id, request, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/confirm-receipt")]
|
||||
[Authorize(Policy = "loading.receive")]
|
||||
public async Task<IActionResult> ConfirmReceipt(Guid id, ConfirmReceiptRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ConfirmReceiptAsync(id, request, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/resolve")]
|
||||
[Authorize(Policy = "loading.resolve")]
|
||||
public async Task<IActionResult> Resolve(Guid id, ResolveDiscrepancyRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ResolveAsync(id, request, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.LoadingEvent;
|
||||
|
||||
public record LoadingSheetResponse(
|
||||
Guid Id,
|
||||
Guid FK_RideId,
|
||||
Guid FK_SourceWarehouseId,
|
||||
string WarehouseName,
|
||||
LoadingSheetStatus Status,
|
||||
DateTime? DispatchConfirmedAt,
|
||||
Guid? DispatchConfirmedBy,
|
||||
DateTime? ReceiptConfirmedAt,
|
||||
Guid? ReceiptConfirmedBy,
|
||||
DateTime CreatedAt,
|
||||
List<LoadingSheetItemResponse> Items);
|
||||
|
||||
public record LoadingSheetItemResponse(
|
||||
Guid Id,
|
||||
Guid FK_ItemId,
|
||||
string ItemName,
|
||||
decimal QuantityDispatched,
|
||||
decimal? QuantityReceived,
|
||||
decimal? QuantityResolved);
|
||||
|
||||
public record CreateLoadingSheetRequest(Guid FK_RideId);
|
||||
|
||||
public record SetItemsRequest(List<SetItemInput> Items);
|
||||
public record SetItemInput(Guid FK_ItemId, decimal Quantity);
|
||||
|
||||
public record SetReceiptItemsRequest(List<ReceiptItemInput> Items);
|
||||
public record ReceiptItemInput(Guid FK_ItemId, decimal QuantityReceived);
|
||||
|
||||
public record ConfirmReceiptRequest(int Meterstart);
|
||||
|
||||
public record ResolveDiscrepancyRequest(List<ResolveItemInput> Items, int Meterstart);
|
||||
public record ResolveItemInput(Guid FK_ItemId, decimal QuantityResolved);
|
||||
@@ -0,0 +1,60 @@
|
||||
using Distribution.Data;
|
||||
using Distribution.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.LoadingEvent;
|
||||
|
||||
public class LoadingSheetRepository(AppDBContext context) : ILoadingSheetRepository
|
||||
{
|
||||
public async Task<LoadingSheet?> GetByIdAsync(Guid id) =>
|
||||
await context.LoadingSheets
|
||||
.Include(s => s.SourceWarehouse)
|
||||
.Include(s => s.Items).ThenInclude(i => i.Item)
|
||||
.FirstOrDefaultAsync(s => s.Id == id);
|
||||
|
||||
public async Task<LoadingSheet?> GetActiveByRideIdAsync(Guid rideId) =>
|
||||
await context.LoadingSheets
|
||||
.FirstOrDefaultAsync(s =>
|
||||
s.FK_RideId == rideId &&
|
||||
s.Status != LoadingSheetStatus.ReceiptConfirmed &&
|
||||
s.Status != LoadingSheetStatus.Resolved);
|
||||
|
||||
public async Task<List<LoadingSheet>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, int page, int pageSize) =>
|
||||
await context.LoadingSheets
|
||||
.Include(s => s.SourceWarehouse)
|
||||
.Where(s =>
|
||||
(rideId == null || s.FK_RideId == rideId) &&
|
||||
(status == null || s.Status == status))
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(Guid? rideId, LoadingSheetStatus? status) =>
|
||||
await context.LoadingSheets
|
||||
.CountAsync(s =>
|
||||
(rideId == null || s.FK_RideId == rideId) &&
|
||||
(status == null || s.Status == status));
|
||||
|
||||
public async Task<List<(Guid ItemId, decimal TotalQty)>> GetAggregatedOrderItemsByRouteIdAsync(Guid routeId)
|
||||
{
|
||||
var groups = await context.OrderItems
|
||||
.Where(oi => oi.IsActive && oi.Order.IsActive && oi.Order.Store.FK_RouteId == routeId)
|
||||
.GroupBy(oi => oi.FK_ItemId)
|
||||
.Select(g => new { ItemId = g.Key, TotalQty = g.Sum(oi => (decimal)oi.Quantity) })
|
||||
.ToListAsync();
|
||||
return groups.Select(x => (x.ItemId, x.TotalQty)).ToList();
|
||||
}
|
||||
|
||||
public async Task AddAsync(LoadingSheet sheet) =>
|
||||
await context.LoadingSheets.AddAsync(sheet);
|
||||
|
||||
public void Update(LoadingSheet sheet) =>
|
||||
context.LoadingSheets.Update(sheet);
|
||||
|
||||
public void RemoveItems(IEnumerable<LoadingSheetItem> items) =>
|
||||
context.LoadingSheetItems.RemoveRange(items);
|
||||
|
||||
public async Task AddItemsAsync(IEnumerable<LoadingSheetItem> items) =>
|
||||
await context.LoadingSheetItems.AddRangeAsync(items);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
using Distribution.Features.Ride;
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.LoadingEvent;
|
||||
|
||||
public class LoadingSheetService(
|
||||
ILoadingSheetRepository repo,
|
||||
IRideRepository rideRepo,
|
||||
IStockRepository stockRepo,
|
||||
IUnitOfWork uow)
|
||||
{
|
||||
public async Task<PagedResponse<LoadingSheetResponse>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, int page, int pageSize)
|
||||
{
|
||||
var total = await repo.GetCountAsync(rideId, status);
|
||||
var items = await repo.GetAllAsync(rideId, status, page, pageSize);
|
||||
return new PagedResponse<LoadingSheetResponse>(page, pageSize, total, items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id);
|
||||
return sheet is null ? null : ToResponse(sheet);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> CreateAsync(CreateLoadingSheetRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(request.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.Open)
|
||||
throw new InvalidOperationException("A loading sheet can only be created for an Open ride");
|
||||
|
||||
var existing = await repo.GetActiveByRideIdAsync(request.FK_RideId);
|
||||
if (existing is not null)
|
||||
throw new InvalidOperationException("This ride already has an active loading sheet");
|
||||
|
||||
var sheet = new LoadingSheet
|
||||
{
|
||||
FK_RideId = ride.Id,
|
||||
FK_SourceWarehouseId = ride.FK_SourceWarehouseId,
|
||||
Status = LoadingSheetStatus.Pending
|
||||
};
|
||||
|
||||
if (ride.RideType == RideType.Delivery)
|
||||
{
|
||||
var orderItems = await repo.GetAggregatedOrderItemsByRouteIdAsync(ride.FK_RouteId);
|
||||
foreach (var (itemId, qty) in orderItems)
|
||||
sheet.Items.Add(new LoadingSheetItem { FK_ItemId = itemId, QuantityDispatched = qty });
|
||||
}
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.AddAsync(sheet);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var saved = await repo.GetByIdAsync(sheet.Id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> SetItemsAsync(Guid id, SetItemsRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.Pending)
|
||||
throw new InvalidOperationException("Items can only be changed while the sheet is Pending");
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
repo.RemoveItems(sheet.Items);
|
||||
await repo.AddItemsAsync(request.Items.Select(i => new LoadingSheetItem
|
||||
{
|
||||
FK_LoadingSheetId = sheet.Id,
|
||||
FK_ItemId = i.FK_ItemId,
|
||||
QuantityDispatched = i.Quantity
|
||||
}));
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var saved = await repo.GetByIdAsync(sheet.Id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> ConfirmDispatchAsync(Guid id, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.Pending)
|
||||
throw new InvalidOperationException($"Cannot confirm dispatch for a sheet in {sheet.Status} status");
|
||||
|
||||
if (!sheet.Items.Any(i => i.QuantityDispatched > 0))
|
||||
throw new InvalidOperationException("Sheet must have at least one item with quantity greater than zero");
|
||||
|
||||
sheet.Status = LoadingSheetStatus.DispatchConfirmed;
|
||||
sheet.DispatchConfirmedAt = DateTime.Now;
|
||||
sheet.DispatchConfirmedBy = userId;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(sheet); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> SetReceiptItemsAsync(Guid id, SetReceiptItemsRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.DispatchConfirmed)
|
||||
throw new InvalidOperationException("Receipt quantities can only be set after dispatch is confirmed");
|
||||
|
||||
foreach (var input in request.Items)
|
||||
{
|
||||
var item = sheet.Items.FirstOrDefault(i => i.FK_ItemId == input.FK_ItemId)
|
||||
?? throw new InvalidOperationException($"Item {input.FK_ItemId} is not on this loading sheet");
|
||||
item.QuantityReceived = input.QuantityReceived;
|
||||
}
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(sheet); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> ConfirmReceiptAsync(Guid id, ConfirmReceiptRequest request, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.DispatchConfirmed)
|
||||
throw new InvalidOperationException($"Cannot confirm receipt for a sheet in {sheet.Status} status");
|
||||
|
||||
if (sheet.Items.Any(i => !i.QuantityReceived.HasValue))
|
||||
throw new InvalidOperationException("All items must have a received quantity before confirming receipt");
|
||||
|
||||
var ride = await rideRepo.GetByIdAsync(sheet.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
var hasDiscrepancy = sheet.Items.Any(i => i.QuantityReceived != i.QuantityDispatched);
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (hasDiscrepancy)
|
||||
{
|
||||
sheet.Status = LoadingSheetStatus.DiscrepancyFlagged;
|
||||
}
|
||||
else
|
||||
{
|
||||
sheet.Status = LoadingSheetStatus.ReceiptConfirmed;
|
||||
sheet.ReceiptConfirmedAt = DateTime.Now;
|
||||
sheet.ReceiptConfirmedBy = userId;
|
||||
|
||||
var lines = sheet.Items.Select(i => (i.FK_ItemId, i.QuantityReceived!.Value)).ToList();
|
||||
await ApplyLoadMovementsAsync(sheet, ride.FK_VehicleId, lines, userId);
|
||||
|
||||
ride.Status = RideStatus.Active;
|
||||
ride.ActivatedAt = DateTime.Now;
|
||||
ride.Meterstart = request.Meterstart;
|
||||
rideRepo.Update(ride);
|
||||
}
|
||||
|
||||
repo.Update(sheet);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> ResolveAsync(Guid id, ResolveDiscrepancyRequest request, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.DiscrepancyFlagged)
|
||||
throw new InvalidOperationException($"Cannot resolve a sheet in {sheet.Status} status");
|
||||
|
||||
foreach (var input in request.Items)
|
||||
{
|
||||
var item = sheet.Items.FirstOrDefault(i => i.FK_ItemId == input.FK_ItemId)
|
||||
?? throw new InvalidOperationException($"Item {input.FK_ItemId} is not on this loading sheet");
|
||||
if (input.QuantityResolved < 0)
|
||||
throw new InvalidOperationException("Resolved quantity cannot be negative");
|
||||
item.QuantityResolved = input.QuantityResolved;
|
||||
}
|
||||
|
||||
if (sheet.Items.Any(i => !i.QuantityResolved.HasValue))
|
||||
throw new InvalidOperationException("All items must have a resolved quantity");
|
||||
|
||||
var ride = await rideRepo.GetByIdAsync(sheet.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
sheet.Status = LoadingSheetStatus.Resolved;
|
||||
sheet.ReceiptConfirmedAt = DateTime.Now;
|
||||
sheet.ReceiptConfirmedBy = userId;
|
||||
|
||||
var lines = sheet.Items.Select(i => (i.FK_ItemId, i.QuantityResolved!.Value)).ToList();
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await ApplyLoadMovementsAsync(sheet, ride.FK_VehicleId, lines, userId);
|
||||
|
||||
ride.Status = RideStatus.Active;
|
||||
ride.ActivatedAt = DateTime.Now;
|
||||
ride.Meterstart = request.Meterstart;
|
||||
rideRepo.Update(ride);
|
||||
|
||||
repo.Update(sheet);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
private async Task ApplyLoadMovementsAsync(LoadingSheet sheet, Guid vehicleId, List<(Guid ItemId, decimal Qty)> lines, Guid userId)
|
||||
{
|
||||
foreach (var (itemId, qty) in lines.Where(l => l.Qty > 0))
|
||||
{
|
||||
var warehouseBalance = await stockRepo.GetBalanceAsync(itemId, sheet.FK_SourceWarehouseId)
|
||||
?? throw new InvalidOperationException($"No stock found in warehouse for item {itemId}");
|
||||
if (warehouseBalance.Quantity < qty)
|
||||
throw new InvalidOperationException($"Insufficient warehouse stock for item {itemId}");
|
||||
|
||||
warehouseBalance.Quantity -= qty;
|
||||
warehouseBalance.UpdatedAt = DateTime.Now;
|
||||
stockRepo.UpdateBalance(warehouseBalance);
|
||||
|
||||
var vehicleBalance = await stockRepo.GetBalanceAsync(itemId, vehicleId);
|
||||
if (vehicleBalance is null)
|
||||
{
|
||||
await stockRepo.AddBalanceAsync(new StockBalance
|
||||
{
|
||||
FK_ItemId = itemId,
|
||||
LocationId = vehicleId,
|
||||
LocationType = LocationType.Vehicle,
|
||||
Quantity = qty
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
vehicleBalance.Quantity += qty;
|
||||
vehicleBalance.UpdatedAt = DateTime.Now;
|
||||
stockRepo.UpdateBalance(vehicleBalance);
|
||||
}
|
||||
|
||||
await stockRepo.AddMovementAsync(new StockMovement
|
||||
{
|
||||
FK_ItemId = itemId,
|
||||
FromLocationId = sheet.FK_SourceWarehouseId,
|
||||
FromLocationType = LocationType.Warehouse,
|
||||
ToLocationId = vehicleId,
|
||||
ToLocationType = LocationType.Vehicle,
|
||||
Quantity = qty,
|
||||
Type = MovementType.Load,
|
||||
ReferenceId = sheet.Id,
|
||||
CreatedBy = userId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static LoadingSheetResponse ToResponse(LoadingSheet s) =>
|
||||
new(s.Id, s.FK_RideId, s.FK_SourceWarehouseId,
|
||||
s.SourceWarehouse?.Name ?? string.Empty,
|
||||
s.Status,
|
||||
s.DispatchConfirmedAt, s.DispatchConfirmedBy,
|
||||
s.ReceiptConfirmedAt, s.ReceiptConfirmedBy,
|
||||
s.CreatedAt,
|
||||
s.Items.Select(i => new LoadingSheetItemResponse(
|
||||
i.Id, i.FK_ItemId, i.Item?.Name ?? string.Empty,
|
||||
i.QuantityDispatched, i.QuantityReceived, i.QuantityResolved)).ToList());
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
namespace Distribution.Features.Order;
|
||||
|
||||
public record OrderItemRequest(Guid ItemId, int Quantity);
|
||||
public record OrderItemRequest(Guid ItemId, int Quantity, decimal? UnitPrice = null);
|
||||
|
||||
public record CreateOrderRequest(Guid StoreId, DateTime OrderDate, decimal TotalAmount, List<OrderItemRequest> Items);
|
||||
|
||||
public record UpdateOrderRequest(DateTime OrderDate, decimal TotalAmount);
|
||||
|
||||
public record OrderItemResponse(Guid ItemId, int Quantity);
|
||||
public record OrderItemResponse(Guid ItemId, int Quantity, decimal UnitPrice);
|
||||
|
||||
public record OrderResponse(
|
||||
Guid Id,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Distribution.Features.Item;
|
||||
using Distribution.Features.PriceList;
|
||||
using Distribution.Features.Store;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
@@ -9,6 +11,8 @@ namespace Distribution.Features.Order;
|
||||
public class OrderService(
|
||||
IOrderRepository repo,
|
||||
IStoreRepository storeRepo,
|
||||
IItemRepository itemRepo,
|
||||
PriceListService priceListService,
|
||||
IUnitOfWork uow,
|
||||
ICurrentUserService currentUser,
|
||||
IScopeAccessService scopeAccess,
|
||||
@@ -18,7 +22,7 @@ public class OrderService(
|
||||
|
||||
private static OrderResponse ToResponse(Models.Order o, List<Models.OrderItem> items) =>
|
||||
new(o.Id, o.OrderDate, o.FK_StoreId, o.TotalAmount,
|
||||
items.Select(i => new OrderItemResponse(i.FK_ItemId, i.Quantity)).ToList(),
|
||||
items.Select(i => new OrderItemResponse(i.FK_ItemId, i.Quantity, i.UnitPrice)).ToList(),
|
||||
o.IsActive, o.CreatedAt);
|
||||
|
||||
private bool HasGlobalScope => currentUser.RoleLevel >= GlobalScopeRoleLevel;
|
||||
@@ -29,6 +33,29 @@ public class OrderService(
|
||||
return await scopeAccess.HasStoreScopeAsync(currentUser.UserId.Value, storeId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// applyPricingAndDiscounts (price-list half, 14_pricing_and_suppliers.md): resolves the
|
||||
/// region-scoped active price list, then global, then Item.SalePrice, and validates any
|
||||
/// caller-supplied override falls within [MinPrice ?? Price, Price]. Returns null if no price
|
||||
/// can be resolved, or if the requested price is outside the allowed band.
|
||||
/// </summary>
|
||||
private async Task<decimal?> ResolveUnitPriceAsync(Guid itemId, decimal? requestedUnitPrice, Models.Store store, DateTime orderDate)
|
||||
{
|
||||
var item = await itemRepo.GetByIdAsync(itemId);
|
||||
if (item is null) return null;
|
||||
var regionId = store.Route?.FK_RegionId;
|
||||
var resolution = await priceListService.ResolvePriceAsync(itemId, regionId, item.SalePrice, orderDate);
|
||||
if (resolution is null) return null;
|
||||
|
||||
if (!requestedUnitPrice.HasValue) return resolution.Price;
|
||||
|
||||
var min = resolution.MinPrice ?? resolution.Price;
|
||||
var max = resolution.Price;
|
||||
if (requestedUnitPrice.Value < min || requestedUnitPrice.Value > max) return null;
|
||||
|
||||
return requestedUnitPrice.Value;
|
||||
}
|
||||
|
||||
public async Task<List<OrderResponse>> GetAllAsync()
|
||||
{
|
||||
var orders = (await repo.GetAllAsync()).Where(o => o.IsActive).ToList();
|
||||
@@ -72,7 +99,7 @@ public class OrderService(
|
||||
{
|
||||
if (!await HasStoreScopeAsync(request.StoreId)) return null;
|
||||
|
||||
var store = await storeRepo.GetByIdAsync(request.StoreId);
|
||||
var store = await storeRepo.GetByIdWithRegionAsync(request.StoreId);
|
||||
if (store is null || !store.IsActive) return null;
|
||||
if (store.KycStatus != KycStatus.Verified)
|
||||
{
|
||||
@@ -86,12 +113,20 @@ public class OrderService(
|
||||
OrderDate = request.OrderDate,
|
||||
TotalAmount = request.TotalAmount
|
||||
};
|
||||
var orderItems = request.Items.Select(i => new Models.OrderItem
|
||||
var orderItems = new List<Models.OrderItem>();
|
||||
foreach (var i in request.Items)
|
||||
{
|
||||
FK_OrderId = order.Id,
|
||||
FK_ItemId = i.ItemId,
|
||||
Quantity = i.Quantity
|
||||
}).ToList();
|
||||
var unitPrice = await ResolveUnitPriceAsync(i.ItemId, i.UnitPrice, store, request.OrderDate);
|
||||
if (unitPrice is null) return null;
|
||||
|
||||
orderItems.Add(new Models.OrderItem
|
||||
{
|
||||
FK_OrderId = order.Id,
|
||||
FK_ItemId = i.ItemId,
|
||||
Quantity = i.Quantity,
|
||||
UnitPrice = unitPrice.Value
|
||||
});
|
||||
}
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace Distribution.Features.PriceList;
|
||||
|
||||
public interface IPriceListRepository
|
||||
{
|
||||
Task<Models.PriceList?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.PriceList>> GetAllAsync(Guid? regionId = null);
|
||||
Task AddAsync(Models.PriceList entity);
|
||||
void Update(Models.PriceList entity);
|
||||
void Remove(Models.PriceList entity);
|
||||
|
||||
Task<Models.PriceListItem?> GetItemAsync(Guid priceListId, Guid itemId);
|
||||
Task AddItemAsync(Models.PriceListItem entity);
|
||||
void UpdateItem(Models.PriceListItem entity);
|
||||
void RemoveItem(Models.PriceListItem entity);
|
||||
|
||||
/// <summary>
|
||||
/// Active PriceListItem rows for the given item and region (region null = global lists only),
|
||||
/// whose parent PriceList is active and effective on orderDate. Most recently created first.
|
||||
/// </summary>
|
||||
Task<List<Models.PriceListItem>> GetActiveItemsAsync(Guid itemId, Guid? regionId, DateTime orderDate);
|
||||
|
||||
/// <summary>
|
||||
/// Active PriceListItem rows for itemId under any PriceList with the given RegionId (null = global),
|
||||
/// whose date range overlaps [effectiveFrom, effectiveTo], excluding a given PriceList.
|
||||
/// </summary>
|
||||
Task<bool> HasOverlapAsync(Guid itemId, Guid? regionId, DateTime effectiveFrom, DateTime effectiveTo, Guid? excludePriceListId);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.PriceList;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/price-lists")]
|
||||
[Authorize]
|
||||
public class PriceListController(PriceListService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] Guid? regionId) =>
|
||||
Ok(await service.GetAllAsync(regionId));
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(CreatePriceListRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdatePriceListRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
return deleted ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/items/{sku}")]
|
||||
public async Task<IActionResult> UpsertItem(Guid id, string sku, UpsertPriceListItemRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.UpsertItemAsync(id, sku, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}/items/{sku}")]
|
||||
public async Task<IActionResult> RemoveItem(Guid id, string sku, CancellationToken ct)
|
||||
{
|
||||
var result = await service.RemoveItemAsync(id, sku, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace Distribution.Features.PriceList;
|
||||
|
||||
public record CreatePriceListRequest(string Name, Guid? RegionId, DateTime EffectiveFrom, DateTime EffectiveTo);
|
||||
|
||||
public record UpdatePriceListRequest(string Name, Guid? RegionId, DateTime EffectiveFrom, DateTime EffectiveTo);
|
||||
|
||||
public record UpsertPriceListItemRequest(decimal Price, decimal? MinPrice = null);
|
||||
|
||||
public record PriceListItemResponse(Guid Id, Guid ItemId, string Sku, string ItemName, decimal Price, decimal? MinPrice);
|
||||
|
||||
/// <summary>
|
||||
/// A resolved price with its negotiable floor. MinPrice null = no negotiation, Price is fixed.
|
||||
/// </summary>
|
||||
public record PriceResolution(decimal Price, decimal? MinPrice);
|
||||
|
||||
public record PriceListResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
Guid? RegionId,
|
||||
string? RegionName,
|
||||
DateTime EffectiveFrom,
|
||||
DateTime EffectiveTo,
|
||||
bool IsActive,
|
||||
DateTime CreatedAt,
|
||||
List<PriceListItemResponse> Items);
|
||||
@@ -0,0 +1,76 @@
|
||||
using Distribution.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.PriceList;
|
||||
|
||||
public class PriceListRepository(AppDBContext context) : IPriceListRepository
|
||||
{
|
||||
public async Task<Models.PriceList?> GetByIdAsync(Guid id) =>
|
||||
await context.PriceLists
|
||||
.Include(pl => pl.Region)
|
||||
.Include(pl => pl.Items.Where(i => i.IsActive)).ThenInclude(i => i.Item)
|
||||
.FirstOrDefaultAsync(pl => pl.Id == id);
|
||||
|
||||
public async Task<List<Models.PriceList>> GetAllAsync(Guid? regionId = null)
|
||||
{
|
||||
var query = context.PriceLists
|
||||
.Include(pl => pl.Region)
|
||||
.Where(pl => pl.IsActive);
|
||||
|
||||
if (regionId.HasValue) query = query.Where(pl => pl.FK_RegionId == regionId);
|
||||
|
||||
return await query.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task AddAsync(Models.PriceList entity) =>
|
||||
await context.PriceLists.AddAsync(entity);
|
||||
|
||||
public void Update(Models.PriceList entity) =>
|
||||
context.PriceLists.Update(entity);
|
||||
|
||||
public void Remove(Models.PriceList entity)
|
||||
{
|
||||
entity.IsActive = false;
|
||||
context.PriceLists.Update(entity);
|
||||
}
|
||||
|
||||
public async Task<Models.PriceListItem?> GetItemAsync(Guid priceListId, Guid itemId) =>
|
||||
await context.PriceListItems
|
||||
.FirstOrDefaultAsync(i => i.FK_PriceListId == priceListId && i.FK_ItemId == itemId && i.IsActive);
|
||||
|
||||
public async Task AddItemAsync(Models.PriceListItem entity) =>
|
||||
await context.PriceListItems.AddAsync(entity);
|
||||
|
||||
public void UpdateItem(Models.PriceListItem entity) =>
|
||||
context.PriceListItems.Update(entity);
|
||||
|
||||
public void RemoveItem(Models.PriceListItem entity)
|
||||
{
|
||||
entity.IsActive = false;
|
||||
context.PriceListItems.Update(entity);
|
||||
}
|
||||
|
||||
public async Task<List<Models.PriceListItem>> GetActiveItemsAsync(Guid itemId, Guid? regionId, DateTime orderDate) =>
|
||||
await context.PriceListItems
|
||||
.Include(i => i.PriceList)
|
||||
.Where(i => i.IsActive
|
||||
&& i.FK_ItemId == itemId
|
||||
&& i.PriceList.IsActive
|
||||
&& i.PriceList.FK_RegionId == regionId
|
||||
&& i.PriceList.EffectiveFrom <= orderDate
|
||||
&& i.PriceList.EffectiveTo >= orderDate)
|
||||
.OrderByDescending(i => i.PriceList.CreatedAt)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<bool> HasOverlapAsync(Guid itemId, Guid? regionId, DateTime effectiveFrom, DateTime effectiveTo, Guid? excludePriceListId) =>
|
||||
await context.PriceListItems
|
||||
.Include(i => i.PriceList)
|
||||
.Where(i => i.IsActive
|
||||
&& i.FK_ItemId == itemId
|
||||
&& i.PriceList.IsActive
|
||||
&& i.PriceList.FK_RegionId == regionId
|
||||
&& (excludePriceListId == null || i.FK_PriceListId != excludePriceListId)
|
||||
&& i.PriceList.EffectiveFrom <= effectiveTo
|
||||
&& i.PriceList.EffectiveTo >= effectiveFrom)
|
||||
.AnyAsync();
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
using Distribution.Features.Item;
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.PriceList;
|
||||
|
||||
public class PriceListService(IPriceListRepository repo, IItemRepository itemRepo, IUnitOfWork uow)
|
||||
{
|
||||
private static PriceListItemResponse MapItem(Models.PriceListItem i) =>
|
||||
new(i.Id, i.FK_ItemId, i.Item.Sku, i.Item.Name, i.Price, i.MinPrice);
|
||||
|
||||
private static PriceListResponse MapDetail(Models.PriceList pl) =>
|
||||
new(pl.Id, pl.Name, pl.FK_RegionId, pl.Region?.Name,
|
||||
pl.EffectiveFrom, pl.EffectiveTo, pl.IsActive, pl.CreatedAt,
|
||||
pl.Items.Where(i => i.IsActive).Select(MapItem).ToList());
|
||||
|
||||
public async Task<List<PriceListResponse>> GetAllAsync(Guid? regionId = null)
|
||||
{
|
||||
var lists = await repo.GetAllAsync(regionId);
|
||||
return lists.Select(pl => new PriceListResponse(
|
||||
pl.Id, pl.Name, pl.FK_RegionId, pl.Region?.Name,
|
||||
pl.EffectiveFrom, pl.EffectiveTo, pl.IsActive, pl.CreatedAt, [])).ToList();
|
||||
}
|
||||
|
||||
public async Task<PriceListResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var pl = await repo.GetByIdAsync(id);
|
||||
if (pl is null || !pl.IsActive) return null;
|
||||
return MapDetail(pl);
|
||||
}
|
||||
|
||||
public async Task<PriceListResponse> CreateAsync(CreatePriceListRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var priceList = new Models.PriceList
|
||||
{
|
||||
Name = request.Name,
|
||||
FK_RegionId = request.RegionId,
|
||||
EffectiveFrom = request.EffectiveFrom,
|
||||
EffectiveTo = request.EffectiveTo
|
||||
};
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { await repo.AddAsync(priceList); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(priceList.Id))!;
|
||||
}
|
||||
|
||||
public async Task<PriceListResponse?> UpdateAsync(Guid id, UpdatePriceListRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var priceList = await repo.GetByIdAsync(id);
|
||||
if (priceList is null || !priceList.IsActive) return null;
|
||||
|
||||
foreach (var item in priceList.Items.Where(i => i.IsActive))
|
||||
{
|
||||
if (await repo.HasOverlapAsync(item.FK_ItemId, request.RegionId, request.EffectiveFrom, request.EffectiveTo, id))
|
||||
throw new InvalidOperationException(
|
||||
$"Overlapping price list already exists for item '{item.Item.Sku}' in the same region for the requested date range.");
|
||||
}
|
||||
|
||||
priceList.Name = request.Name;
|
||||
priceList.FK_RegionId = request.RegionId;
|
||||
priceList.EffectiveFrom = request.EffectiveFrom;
|
||||
priceList.EffectiveTo = request.EffectiveTo;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(priceList); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(id))!;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var priceList = await repo.GetByIdAsync(id);
|
||||
if (priceList is null || !priceList.IsActive) return false;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
foreach (var item in priceList.Items.Where(i => i.IsActive))
|
||||
repo.RemoveItem(item);
|
||||
repo.Remove(priceList);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<PriceListResponse?> UpsertItemAsync(Guid priceListId, string sku, UpsertPriceListItemRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var priceList = await repo.GetByIdAsync(priceListId);
|
||||
if (priceList is null || !priceList.IsActive) return null;
|
||||
|
||||
var item = await itemRepo.GetBySkuAsync(sku);
|
||||
if (item is null) return null;
|
||||
|
||||
if (request.MinPrice.HasValue && request.MinPrice.Value > request.Price)
|
||||
throw new InvalidOperationException(
|
||||
$"MinPrice ({request.MinPrice}) cannot exceed Price ({request.Price}) for item '{sku}'.");
|
||||
|
||||
if (await repo.HasOverlapAsync(item.Id, priceList.FK_RegionId, priceList.EffectiveFrom, priceList.EffectiveTo, priceListId))
|
||||
throw new InvalidOperationException(
|
||||
$"Overlapping price list already exists for item '{sku}' in the same region for this date range.");
|
||||
|
||||
var existing = await repo.GetItemAsync(priceListId, item.Id);
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (existing is null)
|
||||
{
|
||||
await repo.AddItemAsync(new Models.PriceListItem
|
||||
{
|
||||
FK_PriceListId = priceListId,
|
||||
FK_ItemId = item.Id,
|
||||
Price = request.Price,
|
||||
MinPrice = request.MinPrice
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
existing.Price = request.Price;
|
||||
existing.MinPrice = request.MinPrice;
|
||||
repo.UpdateItem(existing);
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(priceListId))!;
|
||||
}
|
||||
|
||||
public async Task<PriceListResponse?> RemoveItemAsync(Guid priceListId, string sku, CancellationToken ct = default)
|
||||
{
|
||||
var priceList = await repo.GetByIdAsync(priceListId);
|
||||
if (priceList is null || !priceList.IsActive) return null;
|
||||
|
||||
var item = await itemRepo.GetBySkuAsync(sku);
|
||||
if (item is null) return null;
|
||||
|
||||
var existing = await repo.GetItemAsync(priceListId, item.Id);
|
||||
if (existing is null) return null;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.RemoveItem(existing); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(priceListId))!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// applyPricingAndDiscounts (price-list half): region-scoped active price list -> global
|
||||
/// active price list -> Item.SalePrice -> null if none apply. The returned PriceResolution
|
||||
/// carries MinPrice so the caller can validate a negotiated UnitPrice against the band;
|
||||
/// the Item.SalePrice fallback has no MinPrice (fixed, non-negotiable).
|
||||
/// </summary>
|
||||
public async Task<PriceResolution?> ResolvePriceAsync(Guid itemId, Guid? regionId, decimal? itemSalePrice, DateTime orderDate)
|
||||
{
|
||||
if (regionId.HasValue)
|
||||
{
|
||||
var regionMatches = await repo.GetActiveItemsAsync(itemId, regionId, orderDate);
|
||||
if (regionMatches.Count > 0) return new PriceResolution(regionMatches[0].Price, regionMatches[0].MinPrice);
|
||||
}
|
||||
|
||||
var globalMatches = await repo.GetActiveItemsAsync(itemId, null, orderDate);
|
||||
if (globalMatches.Count > 0) return new PriceResolution(globalMatches[0].Price, globalMatches[0].MinPrice);
|
||||
|
||||
return itemSalePrice.HasValue ? new PriceResolution(itemSalePrice.Value, null) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
public interface IRideCancelRequestRepository
|
||||
{
|
||||
Task<RideCancelRequest?> GetByIdAsync(Guid id);
|
||||
Task<RideCancelRequest?> GetByRideIdAsync(Guid rideId);
|
||||
Task<RideCancelRequest?> GetPendingByRideIdAsync(Guid rideId);
|
||||
Task<List<RideCancelRequest>> GetAllAsync(CancelRequestStatus? status, int page, int pageSize);
|
||||
Task<int> GetCountAsync(CancelRequestStatus? status);
|
||||
Task AddAsync(RideCancelRequest request);
|
||||
void Update(RideCancelRequest request);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
public interface IRideRepository
|
||||
{
|
||||
Task<DeliveryRun?> GetByIdAsync(Guid id);
|
||||
Task<List<DeliveryRun>> GetAllAsync(RideStatus? status, RideType? type, Guid? driverProfileId, Guid? vehicleId, int page, int pageSize);
|
||||
Task<int> GetCountAsync(RideStatus? status, RideType? type, Guid? driverProfileId, Guid? vehicleId);
|
||||
Task<bool> HasOpenOrActiveRideForVehicleAsync(Guid vehicleId, Guid? excludeRideId = null);
|
||||
Task<List<DeliveryRun>> GetActiveRidesAsync(Guid? excludeRideId = null);
|
||||
Task<List<OrderSummaryModel>> GetActiveOrdersByRouteIdAsync(Guid routeId);
|
||||
Task AddAsync(DeliveryRun ride);
|
||||
void Update(DeliveryRun ride);
|
||||
}
|
||||
|
||||
public record OrderSummaryModel(
|
||||
Guid Id,
|
||||
Guid StoreId,
|
||||
string StoreName,
|
||||
DateTime OrderDate,
|
||||
decimal TotalAmount);
|
||||
@@ -0,0 +1,39 @@
|
||||
using Distribution.Data;
|
||||
using Distribution.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
public class RideCancelRequestRepository(AppDBContext context) : IRideCancelRequestRepository
|
||||
{
|
||||
public async Task<RideCancelRequest?> GetByIdAsync(Guid id) =>
|
||||
await context.RideCancelRequests.FirstOrDefaultAsync(r => r.Id == id);
|
||||
|
||||
public async Task<RideCancelRequest?> GetByRideIdAsync(Guid rideId) =>
|
||||
await context.RideCancelRequests
|
||||
.Where(r => r.FK_RideId == rideId)
|
||||
.OrderByDescending(r => r.RequestedAt)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
public async Task<RideCancelRequest?> GetPendingByRideIdAsync(Guid rideId) =>
|
||||
await context.RideCancelRequests
|
||||
.FirstOrDefaultAsync(r => r.FK_RideId == rideId && r.Status == CancelRequestStatus.Pending);
|
||||
|
||||
public async Task<List<RideCancelRequest>> GetAllAsync(CancelRequestStatus? status, int page, int pageSize) =>
|
||||
await context.RideCancelRequests
|
||||
.Where(r => status == null || r.Status == status)
|
||||
.OrderByDescending(r => r.RequestedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(CancelRequestStatus? status) =>
|
||||
await context.RideCancelRequests
|
||||
.CountAsync(r => status == null || r.Status == status);
|
||||
|
||||
public async Task AddAsync(RideCancelRequest request) =>
|
||||
await context.RideCancelRequests.AddAsync(request);
|
||||
|
||||
public void Update(RideCancelRequest request) =>
|
||||
context.RideCancelRequests.Update(request);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/rides")]
|
||||
[Authorize]
|
||||
public class RideController(RideService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] RideStatus? status,
|
||||
[FromQuery] RideType? type,
|
||||
[FromQuery] Guid? driverProfileId,
|
||||
[FromQuery] Guid? vehicleId,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(status, type, driverProfileId, vehicleId, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "rides.create")]
|
||||
public async Task<IActionResult> Create(CreateRideRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/driver")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> AssignDriver(Guid id, AssignRideDriverRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.AssignDriverAsync(id, request.FK_DriverProfileId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/open")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> Open(Guid id, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.OpenAsync(id, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/activate")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> Activate(Guid id, ActivateRideRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.ActivateAsync(id, request, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/close")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> Close(Guid id, CloseRideRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.CloseAsync(id, request, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/cancel-request")]
|
||||
[Authorize(Policy = "rides.cancel.request")]
|
||||
public async Task<IActionResult> RaiseCancelRequest(Guid id, RaiseCancelRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.RaiseCancelRequestAsync(id, request, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("cancel-requests")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetCancelRequests(
|
||||
[FromQuery] CancelRequestStatus? status,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetCancelRequestsAsync(status, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("cancel-requests/{id:guid}/approve")]
|
||||
[Authorize(Policy = "rides.cancel.approve")]
|
||||
public async Task<IActionResult> ApproveCancelRequest(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ApproveCancelAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("cancel-requests/{id:guid}/reject")]
|
||||
[Authorize(Policy = "rides.cancel.approve")]
|
||||
public async Task<IActionResult> RejectCancelRequest(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.RejectCancelAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/cancel-request")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetCancelRequest(Guid id)
|
||||
{
|
||||
var result = await service.GetCancelRequestAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("breakdown-assist/{rideId:guid}")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetBreakdownAssist(Guid rideId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.GetBreakdownAssistAsync(rideId);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Distribution.Models;
|
||||
using Distribution.Features.Stock;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
// Ride (DeliveryRun)
|
||||
public record RideResponse(
|
||||
Guid Id,
|
||||
RideType RideType,
|
||||
RideStatus Status,
|
||||
Guid VehicleId,
|
||||
string VehicleNumberPlate,
|
||||
Guid DriverProfileId,
|
||||
string DriverFullName,
|
||||
Guid RouteId,
|
||||
string RouteName,
|
||||
Guid SourceWarehouseId,
|
||||
string SourceWarehouseName,
|
||||
int Meterstart,
|
||||
int Meterend,
|
||||
DateTime? StartedAt,
|
||||
DateTime? ActivatedAt,
|
||||
DateTime? ClosedAt,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateRideRequest(
|
||||
RideType RideType,
|
||||
Guid FK_VehicleId,
|
||||
Guid FK_DriverProfileId,
|
||||
Guid FK_RouteId,
|
||||
Guid? FK_SourceWarehouseId);
|
||||
|
||||
public record AssignRideDriverRequest(Guid FK_DriverProfileId);
|
||||
|
||||
public record ActivateRideRequest(int Meterstart);
|
||||
|
||||
public record CloseRideRequest(int Meterend);
|
||||
|
||||
public record RaiseCancelRequest(CancelRequestType TypeCode, string Reason);
|
||||
|
||||
// Cancel Request
|
||||
public record RideCancelRequestResponse(
|
||||
Guid Id,
|
||||
Guid RideId,
|
||||
CancelRequestType TypeCode,
|
||||
string Reason,
|
||||
Guid RequestedBy,
|
||||
DateTime RequestedAt,
|
||||
CancelRequestStatus Status,
|
||||
Guid? ApprovedBy,
|
||||
DateTime? ApprovedAt);
|
||||
|
||||
public record BreakdownAssistRideResponse(
|
||||
Guid RideId,
|
||||
Guid VehicleId,
|
||||
string VehicleNumberPlate,
|
||||
Guid DriverProfileId,
|
||||
string DriverFullName,
|
||||
Guid RouteId,
|
||||
string RouteName,
|
||||
List<StockBalanceResponse> StockLevels);
|
||||
|
||||
public record BreakdownAssistOrderResponse(
|
||||
Guid OrderId,
|
||||
Guid StoreId,
|
||||
string StoreName,
|
||||
DateTime OrderDate,
|
||||
decimal TotalAmount);
|
||||
|
||||
public record BreakdownAssistResponse(
|
||||
Guid RideId,
|
||||
List<BreakdownAssistRideResponse> ActiveRides,
|
||||
List<BreakdownAssistOrderResponse> OpenOrders);
|
||||
@@ -0,0 +1,72 @@
|
||||
using Distribution.Data;
|
||||
using Distribution.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
public class RideRepository(AppDBContext context) : IRideRepository
|
||||
{
|
||||
public async Task<DeliveryRun?> GetByIdAsync(Guid id) =>
|
||||
await context.DeliveryRuns
|
||||
.Include(r => r.Vehicle)
|
||||
.Include(r => r.DriverProfile).ThenInclude(dp => dp.User)
|
||||
.Include(r => r.Route)
|
||||
.Include(r => r.SourceWarehouse)
|
||||
.FirstOrDefaultAsync(r => r.Id == id);
|
||||
|
||||
public async Task<List<DeliveryRun>> GetAllAsync(RideStatus? status, RideType? type, Guid? driverProfileId, Guid? vehicleId, int page, int pageSize) =>
|
||||
await context.DeliveryRuns
|
||||
.Include(r => r.Vehicle)
|
||||
.Include(r => r.DriverProfile).ThenInclude(dp => dp.User)
|
||||
.Include(r => r.Route)
|
||||
.Include(r => r.SourceWarehouse)
|
||||
.Where(r =>
|
||||
(status == null || r.Status == status) &&
|
||||
(type == null || r.RideType == type) &&
|
||||
(driverProfileId == null || r.FK_DriverProfileId == driverProfileId) &&
|
||||
(vehicleId == null || r.FK_VehicleId == vehicleId))
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(RideStatus? status, RideType? type, Guid? driverProfileId, Guid? vehicleId) =>
|
||||
await context.DeliveryRuns
|
||||
.CountAsync(r =>
|
||||
(status == null || r.Status == status) &&
|
||||
(type == null || r.RideType == type) &&
|
||||
(driverProfileId == null || r.FK_DriverProfileId == driverProfileId) &&
|
||||
(vehicleId == null || r.FK_VehicleId == vehicleId));
|
||||
|
||||
public async Task<bool> HasOpenOrActiveRideForVehicleAsync(Guid vehicleId, Guid? excludeRideId = null) =>
|
||||
await context.DeliveryRuns.AnyAsync(r =>
|
||||
r.FK_VehicleId == vehicleId &&
|
||||
r.Id != excludeRideId &&
|
||||
(r.Status == RideStatus.Open || r.Status == RideStatus.Active));
|
||||
|
||||
public async Task<List<DeliveryRun>> GetActiveRidesAsync(Guid? excludeRideId = null) =>
|
||||
await context.DeliveryRuns
|
||||
.Include(r => r.Vehicle)
|
||||
.Include(r => r.DriverProfile).ThenInclude(dp => dp.User)
|
||||
.Include(r => r.Route)
|
||||
.Where(r => r.Id != excludeRideId && r.Status == RideStatus.Active)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<List<OrderSummaryModel>> GetActiveOrdersByRouteIdAsync(Guid routeId) =>
|
||||
await context.Orders
|
||||
.Include(o => o.Store)
|
||||
.Where(o => o.IsActive && o.Store.FK_RouteId == routeId)
|
||||
.OrderByDescending(o => o.OrderDate)
|
||||
.Select(o => new OrderSummaryModel(
|
||||
o.Id,
|
||||
o.FK_StoreId,
|
||||
o.Store.StoreName,
|
||||
o.OrderDate,
|
||||
o.TotalAmount))
|
||||
.ToListAsync();
|
||||
|
||||
public async Task AddAsync(DeliveryRun ride) =>
|
||||
await context.DeliveryRuns.AddAsync(ride);
|
||||
|
||||
public void Update(DeliveryRun ride) =>
|
||||
context.DeliveryRuns.Update(ride);
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Features.DriverComplianceConfig;
|
||||
using Distribution.Features.DriverProfile;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
public class RideService(
|
||||
IRideRepository rideRepo,
|
||||
IDriverProfileRepository driverRepo,
|
||||
IDriverComplianceConfigRepository complianceRepo,
|
||||
IRideCancelRequestRepository cancelRepo,
|
||||
Features.Vehicle.IVehicleRepository vehicleRepo,
|
||||
IStockRepository stockRepo,
|
||||
IUnitOfWork uow)
|
||||
{
|
||||
public async Task<PagedResponse<RideResponse>> GetAllAsync(
|
||||
RideStatus? status,
|
||||
RideType? type,
|
||||
Guid? driverProfileId,
|
||||
Guid? vehicleId,
|
||||
int page,
|
||||
int pageSize)
|
||||
{
|
||||
var total = await rideRepo.GetCountAsync(status, type, driverProfileId, vehicleId);
|
||||
var items = await rideRepo.GetAllAsync(status, type, driverProfileId, vehicleId, page, pageSize);
|
||||
return new PagedResponse<RideResponse>(page, pageSize, total, items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<RideResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(id);
|
||||
return ride is null ? null : ToResponse(ride);
|
||||
}
|
||||
|
||||
public async Task<RideResponse> CreateAsync(CreateRideRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var vehicle = await vehicleRepo.GetByIdAsync(request.FK_VehicleId)
|
||||
?? throw new InvalidOperationException("Vehicle not found");
|
||||
|
||||
var sourceWarehouseId = vehicle.DefaultWarehouseId ?? request.FK_SourceWarehouseId;
|
||||
if (!sourceWarehouseId.HasValue)
|
||||
throw new InvalidOperationException("Source warehouse is required for this vehicle");
|
||||
|
||||
var ride = new DeliveryRun
|
||||
{
|
||||
RideType = request.RideType,
|
||||
FK_VehicleId = request.FK_VehicleId,
|
||||
FK_DriverProfileId = request.FK_DriverProfileId,
|
||||
FK_RouteId = request.FK_RouteId,
|
||||
FK_SourceWarehouseId = sourceWarehouseId.Value,
|
||||
Status = RideStatus.Draft
|
||||
};
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await rideRepo.AddAsync(ride);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
|
||||
var saved = await rideRepo.GetByIdAsync(ride.Id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<RideResponse> OpenAsync(Guid rideId, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.Draft)
|
||||
throw new InvalidOperationException($"Cannot open a ride in {ride.Status} status");
|
||||
|
||||
if (await rideRepo.HasOpenOrActiveRideForVehicleAsync(ride.FK_VehicleId, ride.Id))
|
||||
throw new InvalidOperationException("Vehicle already has an open or active ride");
|
||||
|
||||
await CheckDriverComplianceAsync(ride.FK_DriverProfileId);
|
||||
|
||||
ride.Status = RideStatus.Open;
|
||||
ride.StartedAt = DateTime.Now;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { rideRepo.Update(ride); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(ride);
|
||||
}
|
||||
|
||||
public async Task<RideResponse> AssignDriverAsync(Guid rideId, Guid driverProfileId, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.Draft)
|
||||
throw new InvalidOperationException("Driver can only be changed while the ride is in Draft status");
|
||||
|
||||
var driver = await driverRepo.GetByIdAsync(driverProfileId);
|
||||
if (driver is null || !driver.IsActive)
|
||||
throw new InvalidOperationException("Driver profile not found or inactive");
|
||||
|
||||
ride.FK_DriverProfileId = driverProfileId;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { rideRepo.Update(ride); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var saved = await rideRepo.GetByIdAsync(rideId);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<RideResponse> ActivateAsync(Guid rideId, ActivateRideRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.Open)
|
||||
throw new InvalidOperationException($"Cannot activate a ride in {ride.Status} status");
|
||||
|
||||
ride.Status = RideStatus.Active;
|
||||
ride.ActivatedAt = DateTime.Now;
|
||||
ride.Meterstart = request.Meterstart;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { rideRepo.Update(ride); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(ride);
|
||||
}
|
||||
|
||||
public async Task<RideResponse> CloseAsync(Guid rideId, CloseRideRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.Active)
|
||||
throw new InvalidOperationException($"Cannot close a ride in {ride.Status} status");
|
||||
|
||||
await EnsureVehicleStockClearedAsync(ride.FK_VehicleId);
|
||||
|
||||
ride.Status = RideStatus.Closed;
|
||||
ride.ClosedAt = DateTime.Now;
|
||||
ride.Meterend = request.Meterend;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { rideRepo.Update(ride); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(ride);
|
||||
}
|
||||
|
||||
public async Task<RideCancelRequestResponse> RaiseCancelRequestAsync(Guid rideId, RaiseCancelRequest request, Guid requestedBy, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.Active)
|
||||
throw new InvalidOperationException($"Cannot raise a cancel request for a ride in {ride.Status} status");
|
||||
|
||||
var existing = await cancelRepo.GetPendingByRideIdAsync(rideId);
|
||||
if (existing is not null)
|
||||
throw new InvalidOperationException("There is already a pending cancel request for this ride");
|
||||
|
||||
var cancelRequest = new RideCancelRequest
|
||||
{
|
||||
FK_RideId = rideId,
|
||||
TypeCode = request.TypeCode,
|
||||
Reason = request.Reason,
|
||||
RequestedBy = requestedBy,
|
||||
RequestedAt = DateTime.Now,
|
||||
Status = CancelRequestStatus.Pending
|
||||
};
|
||||
|
||||
ride.Status = RideStatus.CancelRequested;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await cancelRepo.AddAsync(cancelRequest);
|
||||
rideRepo.Update(ride);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToCancelResponse(cancelRequest);
|
||||
}
|
||||
|
||||
public async Task<PagedResponse<RideCancelRequestResponse>> GetCancelRequestsAsync(CancelRequestStatus? status, int page, int pageSize)
|
||||
{
|
||||
var total = await cancelRepo.GetCountAsync(status);
|
||||
var items = await cancelRepo.GetAllAsync(status, page, pageSize);
|
||||
return new PagedResponse<RideCancelRequestResponse>(page, pageSize, total, items.Select(ToCancelResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<RideCancelRequestResponse> ApproveCancelAsync(Guid cancelRequestId, Guid approvedBy, CancellationToken ct = default)
|
||||
{
|
||||
var cancelRequest = await cancelRepo.GetByIdAsync(cancelRequestId)
|
||||
?? throw new KeyNotFoundException("Cancel request not found");
|
||||
|
||||
if (cancelRequest.Status != CancelRequestStatus.Pending)
|
||||
throw new InvalidOperationException("Cancel request is not pending");
|
||||
|
||||
var ride = await rideRepo.GetByIdAsync(cancelRequest.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.CancelRequested)
|
||||
throw new InvalidOperationException("Ride is not in CancelRequested status");
|
||||
|
||||
await EnsureVehicleStockClearedAsync(ride.FK_VehicleId);
|
||||
|
||||
cancelRequest.Status = CancelRequestStatus.Approved;
|
||||
cancelRequest.ApprovedBy = approvedBy;
|
||||
cancelRequest.ApprovedAt = DateTime.Now;
|
||||
|
||||
ride.Status = RideStatus.Cancelled;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
cancelRepo.Update(cancelRequest);
|
||||
rideRepo.Update(ride);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToCancelResponse(cancelRequest);
|
||||
}
|
||||
|
||||
public async Task<RideCancelRequestResponse> RejectCancelAsync(Guid cancelRequestId, Guid rejectedBy, CancellationToken ct = default)
|
||||
{
|
||||
var cancelRequest = await cancelRepo.GetByIdAsync(cancelRequestId)
|
||||
?? throw new KeyNotFoundException("Cancel request not found");
|
||||
|
||||
if (cancelRequest.Status != CancelRequestStatus.Pending)
|
||||
throw new InvalidOperationException("Cancel request is not pending");
|
||||
|
||||
var ride = await rideRepo.GetByIdAsync(cancelRequest.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
if (ride.Status != RideStatus.CancelRequested)
|
||||
throw new InvalidOperationException("Ride is not in CancelRequested status");
|
||||
|
||||
cancelRequest.Status = CancelRequestStatus.Rejected;
|
||||
cancelRequest.ApprovedBy = rejectedBy;
|
||||
cancelRequest.ApprovedAt = DateTime.Now;
|
||||
|
||||
// Restore to previous status: Active if ActivatedAt is set, else Open
|
||||
ride.Status = ride.ActivatedAt.HasValue ? RideStatus.Active : RideStatus.Open;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
cancelRepo.Update(cancelRequest);
|
||||
rideRepo.Update(ride);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToCancelResponse(cancelRequest);
|
||||
}
|
||||
|
||||
public async Task<RideCancelRequestResponse?> GetCancelRequestAsync(Guid rideId)
|
||||
{
|
||||
var cancelRequest = await cancelRepo.GetByRideIdAsync(rideId);
|
||||
return cancelRequest is null ? null : ToCancelResponse(cancelRequest);
|
||||
}
|
||||
|
||||
public async Task<BreakdownAssistResponse> GetBreakdownAssistAsync(Guid rideId)
|
||||
{
|
||||
var strandedRide = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
var activeRides = await rideRepo.GetActiveRidesAsync(rideId);
|
||||
var activeRideResponses = new List<BreakdownAssistRideResponse>();
|
||||
|
||||
foreach (var ride in activeRides)
|
||||
{
|
||||
var stockLevels = await stockRepo.GetBalancesByLocationAsync(ride.FK_VehicleId, LocationType.Vehicle);
|
||||
activeRideResponses.Add(new BreakdownAssistRideResponse(
|
||||
ride.Id,
|
||||
ride.FK_VehicleId,
|
||||
ride.Vehicle?.NumberPlate ?? string.Empty,
|
||||
ride.FK_DriverProfileId,
|
||||
ride.DriverProfile?.User?.FullName ?? string.Empty,
|
||||
ride.FK_RouteId,
|
||||
ride.Route?.RouteName ?? string.Empty,
|
||||
stockLevels.Select(b => new StockBalanceResponse(
|
||||
b.FK_ItemId,
|
||||
b.Item.Name,
|
||||
b.LocationId,
|
||||
b.LocationType,
|
||||
b.Quantity,
|
||||
b.UpdatedAt)).ToList()));
|
||||
}
|
||||
|
||||
var openOrders = await rideRepo.GetActiveOrdersByRouteIdAsync(strandedRide.FK_RouteId);
|
||||
|
||||
return new BreakdownAssistResponse(
|
||||
strandedRide.Id,
|
||||
activeRideResponses,
|
||||
openOrders.Select(o => new BreakdownAssistOrderResponse(
|
||||
o.Id,
|
||||
o.StoreId,
|
||||
o.StoreName,
|
||||
o.OrderDate,
|
||||
o.TotalAmount)).ToList());
|
||||
}
|
||||
|
||||
private async Task CheckDriverComplianceAsync(Guid driverProfileId)
|
||||
{
|
||||
var driver = await driverRepo.GetByIdAsync(driverProfileId)
|
||||
?? throw new InvalidOperationException("Driver profile not found");
|
||||
|
||||
if (!driver.IsActive)
|
||||
throw new InvalidOperationException("Driver profile is inactive");
|
||||
|
||||
var config = await complianceRepo.GetAsync();
|
||||
if (config is null) return;
|
||||
|
||||
var today = DateTime.Now.Date;
|
||||
|
||||
if (config.EnforceLicenseExpiry && driver.LicenseExpiry.Date <= today)
|
||||
throw new InvalidOperationException("Driver license has expired");
|
||||
|
||||
if (config.EnforceMedicalClearance && driver.MedicalClearanceExpiry.Date <= today)
|
||||
throw new InvalidOperationException("Driver medical clearance has expired");
|
||||
}
|
||||
|
||||
private async Task EnsureVehicleStockClearedAsync(Guid vehicleId)
|
||||
{
|
||||
var balances = await stockRepo.GetBalancesByLocationAsync(vehicleId, LocationType.Vehicle);
|
||||
if (balances.Any(b => b.Quantity > 0))
|
||||
throw new InvalidOperationException("All vehicle stock must be returned before this ride can be completed");
|
||||
}
|
||||
|
||||
private static RideResponse ToResponse(DeliveryRun r) =>
|
||||
new(r.Id, r.RideType, r.Status,
|
||||
r.FK_VehicleId, r.Vehicle?.NumberPlate ?? string.Empty,
|
||||
r.FK_DriverProfileId, r.DriverProfile?.User?.FullName ?? string.Empty,
|
||||
r.FK_RouteId, r.Route?.RouteName ?? string.Empty,
|
||||
r.FK_SourceWarehouseId, r.SourceWarehouse?.Name ?? string.Empty,
|
||||
r.Meterstart, r.Meterend,
|
||||
r.StartedAt, r.ActivatedAt, r.ClosedAt, r.CreatedAt);
|
||||
|
||||
private static RideCancelRequestResponse ToCancelResponse(RideCancelRequest c) =>
|
||||
new(c.Id, c.FK_RideId, c.TypeCode, c.Reason, c.RequestedBy, c.RequestedAt,
|
||||
c.Status, c.ApprovedBy, c.ApprovedAt);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace Distribution.Features.Scheme;
|
||||
|
||||
public interface ISchemeRepository
|
||||
{
|
||||
Task<Models.Scheme?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.Scheme>> GetAllAsync(Guid? regionId = null);
|
||||
Task AddAsync(Models.Scheme entity);
|
||||
void Update(Models.Scheme entity);
|
||||
void Remove(Models.Scheme entity);
|
||||
|
||||
Task<List<Models.SchemeRedemption>> GetRedemptionsAsync(Guid schemeId);
|
||||
Task AddRedemptionAsync(Models.SchemeRedemption entity);
|
||||
Task<bool> HasRedemptionAsync(Guid schemeId, Guid orderId);
|
||||
|
||||
Task<Models.SchemeBundleComponent?> GetBundleComponentAsync(Guid schemeId, Guid itemId);
|
||||
Task AddBundleComponentAsync(Models.SchemeBundleComponent entity);
|
||||
void UpdateBundleComponent(Models.SchemeBundleComponent entity);
|
||||
void RemoveBundleComponent(Models.SchemeBundleComponent entity);
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Scheme;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/schemes")]
|
||||
[Authorize]
|
||||
public class SchemeController(SchemeService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] Guid? regionId) =>
|
||||
Ok(await service.GetAllAsync(regionId));
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(CreateSchemeRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return BadRequest(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateSchemeRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return BadRequest(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
return deleted ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/free-goods-rule")]
|
||||
public async Task<IActionResult> SetFreeGoodsRule(Guid id, SetFreeGoodsRuleRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.SetFreeGoodsRuleAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}/free-goods-rule")]
|
||||
public async Task<IActionResult> ClearFreeGoodsRule(Guid id, CancellationToken ct)
|
||||
{
|
||||
var result = await service.ClearFreeGoodsRuleAsync(id, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/bundle-components/{itemId:guid}")]
|
||||
public async Task<IActionResult> UpsertBundleComponent(Guid id, Guid itemId, UpsertBundleComponentRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.UpsertBundleComponentAsync(id, itemId, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}/bundle-components/{itemId:guid}")]
|
||||
public async Task<IActionResult> RemoveBundleComponent(Guid id, Guid itemId, CancellationToken ct)
|
||||
{
|
||||
var result = await service.RemoveBundleComponentAsync(id, itemId, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("eligible")]
|
||||
public async Task<IActionResult> GetEligible([FromQuery] Guid storeId, [FromQuery] Guid orderId)
|
||||
{
|
||||
var result = await service.EvaluateEligibilityAsync(storeId, orderId);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/spend")]
|
||||
public async Task<IActionResult> GetSpend(Guid id)
|
||||
{
|
||||
var result = await service.GetSpendAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/roi")]
|
||||
public async Task<IActionResult> GetROI(Guid id)
|
||||
{
|
||||
var result = await service.GetROIAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
[ApiController]
|
||||
[Route("api/orders")]
|
||||
[Authorize]
|
||||
public class SchemeOrderController(SchemeService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("{id:guid}/apply-scheme")]
|
||||
public async Task<IActionResult> ApplyScheme(Guid id, ApplySchemeRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.ApplySchemeAsync(id, request.SchemeId, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Scheme;
|
||||
|
||||
// ── Rule config payloads for percentage-based rules (serialized into Scheme.RuleConfig) ──
|
||||
|
||||
public record SlabDiscountConfig(List<SlabTier> Tiers);
|
||||
|
||||
public record SlabTier(decimal MinOrderAmount, decimal DiscountPercent);
|
||||
|
||||
public record FlatPercentConfig(decimal DiscountPercent);
|
||||
|
||||
// ── Requests ────────────────────────────────────────────────────────────
|
||||
|
||||
public record BundleComponentRequest(Guid ItemId, int Qty);
|
||||
|
||||
/// <summary>
|
||||
/// TriggerItemId/TriggerQty/FreeItemId/FreeQty/BundleComponents are optional so plain discount
|
||||
/// schemes (SlabDiscount/FlatPercent) can omit them entirely. When RuleType is BuyXGetY, supplying
|
||||
/// TriggerItemId+TriggerQty+FreeItemId+FreeQty here creates the scheme fully populated in one call
|
||||
/// instead of a separate PUT .../free-goods-rule. When RuleType is FreeBundle, supplying
|
||||
/// FreeItemId+FreeQty+BundleComponents does the same. These can still be added/edited later via
|
||||
/// PUT .../free-goods-rule and PUT .../bundle-components/{itemId}.
|
||||
/// </summary>
|
||||
public record CreateSchemeRequest(
|
||||
string Name,
|
||||
SchemeRuleType RuleType,
|
||||
string? RuleConfig,
|
||||
Guid? RegionId,
|
||||
string? EligibleSegment,
|
||||
DateTime DateRangeFrom,
|
||||
DateTime DateRangeTo,
|
||||
bool AgentLimitExempt,
|
||||
decimal? BaselineExpectedSales,
|
||||
Guid? TriggerItemId = null,
|
||||
int? TriggerQty = null,
|
||||
Guid? FreeItemId = null,
|
||||
decimal? FreeQty = null,
|
||||
List<BundleComponentRequest>? BundleComponents = null);
|
||||
|
||||
public record UpdateSchemeRequest(
|
||||
string Name,
|
||||
string? RuleConfig,
|
||||
Guid? RegionId,
|
||||
string? EligibleSegment,
|
||||
DateTime DateRangeFrom,
|
||||
DateTime DateRangeTo,
|
||||
bool AgentLimitExempt,
|
||||
decimal? BaselineExpectedSales);
|
||||
|
||||
public record ApplySchemeRequest(Guid SchemeId);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the free-goods payout for a scheme. For BuyXGetY, TriggerItemId/TriggerQty are required
|
||||
/// (what the store must buy); for FreeBundle they are ignored — the required items instead come
|
||||
/// from the scheme's bundle-components CRUD. FreeItemId/FreeQty is the payout in both cases.
|
||||
/// </summary>
|
||||
public record SetFreeGoodsRuleRequest(Guid? TriggerItemId, int? TriggerQty, Guid FreeItemId, decimal FreeQty);
|
||||
|
||||
public record UpsertBundleComponentRequest(int Qty);
|
||||
|
||||
// ── Responses ───────────────────────────────────────────────────────────
|
||||
|
||||
public record BundleComponentResponse(Guid ItemId, string Sku, string ItemName, int Qty);
|
||||
|
||||
public record SchemeResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
SchemeRuleType RuleType,
|
||||
string? RuleConfig,
|
||||
Guid? TriggerItemId,
|
||||
string? TriggerItemName,
|
||||
int? TriggerQty,
|
||||
Guid? FreeItemId,
|
||||
string? FreeItemName,
|
||||
decimal? FreeQty,
|
||||
List<BundleComponentResponse> BundleComponents,
|
||||
Guid? RegionId,
|
||||
string? RegionName,
|
||||
string? EligibleSegment,
|
||||
DateTime DateRangeFrom,
|
||||
DateTime DateRangeTo,
|
||||
bool AgentLimitExempt,
|
||||
decimal? BaselineExpectedSales,
|
||||
bool IsActive,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record SchemeEligibilityResponse(
|
||||
Guid SchemeId,
|
||||
string SchemeName,
|
||||
SchemeRuleType RuleType,
|
||||
bool Eligible,
|
||||
string? Reason,
|
||||
decimal? DiscountAmount,
|
||||
Guid? FreeItemId,
|
||||
decimal? FreeQty);
|
||||
|
||||
public record SchemeRedemptionResponse(
|
||||
Guid Id,
|
||||
Guid SchemeId,
|
||||
Guid? OrderId,
|
||||
decimal? DiscountAmount,
|
||||
Guid? FreeItemId,
|
||||
string? FreeItemName,
|
||||
decimal? FreeQty,
|
||||
decimal? FreeItemCostValue,
|
||||
DateTime RedeemedAt);
|
||||
|
||||
public record SchemeSpendResponse(Guid SchemeId, decimal TotalDiscountSpend, decimal TotalFreeGoodsCostSpend, decimal TotalSpend, int RedemptionCount);
|
||||
|
||||
public record SchemeROIResponse(Guid SchemeId, decimal BaselineExpectedSales, decimal ActualSales, decimal IncrementalSales, decimal TotalSpend, decimal? ROI);
|
||||
@@ -0,0 +1,67 @@
|
||||
using Distribution.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.Scheme;
|
||||
|
||||
public class SchemeRepository(AppDBContext context) : ISchemeRepository
|
||||
{
|
||||
public async Task<Models.Scheme?> GetByIdAsync(Guid id) =>
|
||||
await context.Schemes
|
||||
.Include(s => s.Region)
|
||||
.Include(s => s.TriggerItem)
|
||||
.Include(s => s.FreeItem)
|
||||
.Include(s => s.BundleComponents).ThenInclude(c => c.Item)
|
||||
.FirstOrDefaultAsync(s => s.Id == id);
|
||||
|
||||
public async Task<List<Models.Scheme>> GetAllAsync(Guid? regionId = null)
|
||||
{
|
||||
var query = context.Schemes
|
||||
.Include(s => s.Region)
|
||||
.Include(s => s.TriggerItem)
|
||||
.Include(s => s.FreeItem)
|
||||
.Include(s => s.BundleComponents).ThenInclude(c => c.Item)
|
||||
.Where(s => s.IsActive);
|
||||
|
||||
if (regionId.HasValue) query = query.Where(s => s.FK_RegionId == regionId);
|
||||
|
||||
return await query.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task AddAsync(Models.Scheme entity) =>
|
||||
await context.Schemes.AddAsync(entity);
|
||||
|
||||
public void Update(Models.Scheme entity) =>
|
||||
context.Schemes.Update(entity);
|
||||
|
||||
public void Remove(Models.Scheme entity)
|
||||
{
|
||||
entity.IsActive = false;
|
||||
context.Schemes.Update(entity);
|
||||
}
|
||||
|
||||
public async Task<List<Models.SchemeRedemption>> GetRedemptionsAsync(Guid schemeId) =>
|
||||
await context.SchemeRedemptions
|
||||
.Include(r => r.FreeItem)
|
||||
.Include(r => r.Order)
|
||||
.Where(r => r.FK_SchemeId == schemeId)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task AddRedemptionAsync(Models.SchemeRedemption entity) =>
|
||||
await context.SchemeRedemptions.AddAsync(entity);
|
||||
|
||||
public async Task<bool> HasRedemptionAsync(Guid schemeId, Guid orderId) =>
|
||||
await context.SchemeRedemptions.AnyAsync(r => r.FK_SchemeId == schemeId && r.FK_OrderId == orderId);
|
||||
|
||||
public async Task<Models.SchemeBundleComponent?> GetBundleComponentAsync(Guid schemeId, Guid itemId) =>
|
||||
await context.SchemeBundleComponents
|
||||
.FirstOrDefaultAsync(c => c.FK_SchemeId == schemeId && c.FK_ItemId == itemId);
|
||||
|
||||
public async Task AddBundleComponentAsync(Models.SchemeBundleComponent entity) =>
|
||||
await context.SchemeBundleComponents.AddAsync(entity);
|
||||
|
||||
public void UpdateBundleComponent(Models.SchemeBundleComponent entity) =>
|
||||
context.SchemeBundleComponents.Update(entity);
|
||||
|
||||
public void RemoveBundleComponent(Models.SchemeBundleComponent entity) =>
|
||||
context.SchemeBundleComponents.Remove(entity);
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
using System.Text.Json;
|
||||
using Distribution.Features.Item;
|
||||
using Distribution.Features.Order;
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Features.Store;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Scheme;
|
||||
|
||||
public class SchemeService(
|
||||
ISchemeRepository repo,
|
||||
IOrderRepository orderRepo,
|
||||
IItemRepository itemRepo,
|
||||
IStoreRepository storeRepo,
|
||||
IStockRepository stockRepo,
|
||||
IUnitOfWork uow)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
private static SchemeResponse ToResponse(Models.Scheme s) =>
|
||||
new(s.Id, s.Name, s.RuleType, s.RuleConfig,
|
||||
s.FK_TriggerItemId, s.TriggerItem?.Name, s.TriggerQty,
|
||||
s.FK_FreeItemId, s.FreeItem?.Name, s.FreeQty,
|
||||
s.BundleComponents.Select(c => new BundleComponentResponse(c.FK_ItemId, c.Item.Sku, c.Item.Name, c.Qty)).ToList(),
|
||||
s.FK_RegionId, s.Region?.Name, s.EligibleSegment,
|
||||
s.DateRangeFrom, s.DateRangeTo, s.AgentLimitExempt, s.BaselineExpectedSales, s.IsActive, s.CreatedAt);
|
||||
|
||||
private static SchemeRedemptionResponse ToRedemptionResponse(SchemeRedemption r) =>
|
||||
new(r.Id, r.FK_SchemeId, r.FK_OrderId, r.DiscountAmount, r.FK_FreeItemId, r.FreeItem?.Name,
|
||||
r.FreeQty, r.FreeItemCostValue, r.RedeemedAt);
|
||||
|
||||
// ── CRUD ───────────────────────────────────────────────────────────────
|
||||
|
||||
public async Task<List<SchemeResponse>> GetAllAsync(Guid? regionId = null)
|
||||
{
|
||||
var schemes = await repo.GetAllAsync(regionId);
|
||||
return schemes.Select(ToResponse).ToList();
|
||||
}
|
||||
|
||||
public async Task<SchemeResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(id);
|
||||
return scheme is null || !scheme.IsActive ? null : ToResponse(scheme);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// createScheme(schemeRules, eligibility, dateRange). RuleConfig is only meaningful for
|
||||
/// SlabDiscount/FlatPercent. For BuyXGetY/FreeBundle, the free-goods payout (and bundle
|
||||
/// components) can be supplied inline here to create a fully-populated scheme in one call, or
|
||||
/// added afterwards via SetFreeGoodsRuleAsync / UpsertBundleComponentAsync.
|
||||
/// </summary>
|
||||
public async Task<SchemeResponse> CreateAsync(CreateSchemeRequest request, CancellationToken ct = default)
|
||||
{
|
||||
ValidatePercentRuleConfig(request.RuleType, request.RuleConfig);
|
||||
if (request.DateRangeFrom > request.DateRangeTo)
|
||||
throw new InvalidOperationException("DateRangeFrom must not be after DateRangeTo.");
|
||||
|
||||
var hasFreeGoodsRule = request.FreeItemId.HasValue || request.FreeQty.HasValue ||
|
||||
request.TriggerItemId.HasValue || request.TriggerQty.HasValue;
|
||||
if (hasFreeGoodsRule)
|
||||
await ValidateFreeGoodsRuleAsync(request.RuleType, request.TriggerItemId, request.TriggerQty, request.FreeItemId, request.FreeQty);
|
||||
|
||||
if (request.BundleComponents is { Count: > 0 })
|
||||
{
|
||||
if (request.RuleType != SchemeRuleType.FreeBundle)
|
||||
throw new InvalidOperationException("BundleComponents only applies to FreeBundle schemes.");
|
||||
foreach (var c in request.BundleComponents)
|
||||
{
|
||||
if (c.Qty <= 0)
|
||||
throw new InvalidOperationException("Bundle component Qty must be positive.");
|
||||
if (await itemRepo.GetByIdAsync(c.ItemId) is null)
|
||||
throw new InvalidOperationException($"Bundle component item '{c.ItemId}' not found.");
|
||||
}
|
||||
}
|
||||
|
||||
var scheme = new Models.Scheme
|
||||
{
|
||||
Name = request.Name,
|
||||
RuleType = request.RuleType,
|
||||
RuleConfig = request.RuleConfig,
|
||||
FK_RegionId = request.RegionId,
|
||||
EligibleSegment = request.EligibleSegment,
|
||||
DateRangeFrom = request.DateRangeFrom,
|
||||
DateRangeTo = request.DateRangeTo,
|
||||
AgentLimitExempt = request.AgentLimitExempt,
|
||||
BaselineExpectedSales = request.BaselineExpectedSales
|
||||
};
|
||||
|
||||
if (hasFreeGoodsRule)
|
||||
{
|
||||
scheme.FK_TriggerItemId = request.RuleType == SchemeRuleType.BuyXGetY ? request.TriggerItemId : null;
|
||||
scheme.TriggerQty = request.RuleType == SchemeRuleType.BuyXGetY ? request.TriggerQty : null;
|
||||
scheme.FK_FreeItemId = request.FreeItemId;
|
||||
scheme.FreeQty = request.FreeQty;
|
||||
}
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.AddAsync(scheme);
|
||||
if (request.BundleComponents is { Count: > 0 })
|
||||
{
|
||||
foreach (var c in request.BundleComponents)
|
||||
await repo.AddBundleComponentAsync(new SchemeBundleComponent { FK_SchemeId = scheme.Id, FK_ItemId = c.ItemId, Qty = c.Qty });
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(scheme.Id))!;
|
||||
}
|
||||
|
||||
public async Task<SchemeResponse?> UpdateAsync(Guid id, UpdateSchemeRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(id);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
ValidatePercentRuleConfig(scheme.RuleType, request.RuleConfig);
|
||||
if (request.DateRangeFrom > request.DateRangeTo)
|
||||
throw new InvalidOperationException("DateRangeFrom must not be after DateRangeTo.");
|
||||
|
||||
scheme.Name = request.Name;
|
||||
scheme.RuleConfig = request.RuleConfig;
|
||||
scheme.FK_RegionId = request.RegionId;
|
||||
scheme.EligibleSegment = request.EligibleSegment;
|
||||
scheme.DateRangeFrom = request.DateRangeFrom;
|
||||
scheme.DateRangeTo = request.DateRangeTo;
|
||||
scheme.AgentLimitExempt = request.AgentLimitExempt;
|
||||
scheme.BaselineExpectedSales = request.BaselineExpectedSales;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(scheme); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(scheme);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(id);
|
||||
if (scheme is null || !scheme.IsActive) return false;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Remove(scheme); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Free-goods rule CRUD (BuyXGetY trigger + shared payout) ──────────────
|
||||
|
||||
public async Task<SchemeResponse?> SetFreeGoodsRuleAsync(Guid schemeId, SetFreeGoodsRuleRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
await ValidateFreeGoodsRuleAsync(scheme.RuleType, request.TriggerItemId, request.TriggerQty, request.FreeItemId, request.FreeQty);
|
||||
|
||||
scheme.FK_TriggerItemId = scheme.RuleType == SchemeRuleType.BuyXGetY ? request.TriggerItemId : null;
|
||||
scheme.TriggerQty = scheme.RuleType == SchemeRuleType.BuyXGetY ? request.TriggerQty : null;
|
||||
scheme.FK_FreeItemId = request.FreeItemId;
|
||||
scheme.FreeQty = request.FreeQty;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(scheme); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(schemeId))!;
|
||||
}
|
||||
|
||||
public async Task<SchemeResponse?> ClearFreeGoodsRuleAsync(Guid schemeId, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
scheme.FK_TriggerItemId = null;
|
||||
scheme.TriggerQty = null;
|
||||
scheme.FK_FreeItemId = null;
|
||||
scheme.FreeQty = null;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(scheme); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(schemeId))!;
|
||||
}
|
||||
|
||||
// ── Bundle component CRUD (FreeBundle required items) ────────────────────
|
||||
|
||||
public async Task<SchemeResponse?> UpsertBundleComponentAsync(Guid schemeId, Guid itemId, UpsertBundleComponentRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
if (scheme.RuleType != SchemeRuleType.FreeBundle)
|
||||
throw new InvalidOperationException("Bundle components only apply to FreeBundle schemes.");
|
||||
if (request.Qty <= 0)
|
||||
throw new InvalidOperationException("Qty must be positive.");
|
||||
|
||||
var item = await itemRepo.GetByIdAsync(itemId)
|
||||
?? throw new InvalidOperationException("Item not found.");
|
||||
|
||||
var existing = await repo.GetBundleComponentAsync(schemeId, itemId);
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (existing is null)
|
||||
{
|
||||
await repo.AddBundleComponentAsync(new SchemeBundleComponent
|
||||
{
|
||||
FK_SchemeId = schemeId,
|
||||
FK_ItemId = item.Id,
|
||||
Qty = request.Qty
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
existing.Qty = request.Qty;
|
||||
repo.UpdateBundleComponent(existing);
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(schemeId))!;
|
||||
}
|
||||
|
||||
public async Task<SchemeResponse?> RemoveBundleComponentAsync(Guid schemeId, Guid itemId, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
var existing = await repo.GetBundleComponentAsync(schemeId, itemId);
|
||||
if (existing is null) return null;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.RemoveBundleComponent(existing); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return (await GetByIdAsync(schemeId))!;
|
||||
}
|
||||
|
||||
// ── evaluateSchemeEligibility(storeId, orderId) ──────────────────────────
|
||||
|
||||
public async Task<List<SchemeEligibilityResponse>?> EvaluateEligibilityAsync(Guid storeId, Guid orderId)
|
||||
{
|
||||
var store = await storeRepo.GetByIdWithRegionAsync(storeId);
|
||||
if (store is null || !store.IsActive) return null;
|
||||
|
||||
var order = await orderRepo.GetByIdAsync(orderId);
|
||||
if (order is null || !order.IsActive) return null;
|
||||
|
||||
var orderItems = await orderRepo.GetItemsByOrderIdAsync(orderId);
|
||||
var regionId = store.Route?.FK_RegionId;
|
||||
|
||||
var candidates = await repo.GetAllAsync();
|
||||
var result = new List<SchemeEligibilityResponse>();
|
||||
|
||||
foreach (var scheme in candidates)
|
||||
{
|
||||
if (scheme.FK_RegionId.HasValue && scheme.FK_RegionId != regionId)
|
||||
continue;
|
||||
if (!string.IsNullOrEmpty(scheme.EligibleSegment) &&
|
||||
!string.Equals(scheme.EligibleSegment, store.Segment, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
if (order.OrderDate < scheme.DateRangeFrom || order.OrderDate > scheme.DateRangeTo)
|
||||
continue;
|
||||
|
||||
result.Add(EvaluateRule(scheme, orderItems));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scope-only check (region, segment, date range as of today) with no order to evaluate line
|
||||
/// items against — used by Store Management's `checkStoreSchemeEligibility(storeId, schemeId)`
|
||||
/// (12_store_management.md), which has no order context. Returns null if the store or scheme
|
||||
/// doesn't exist; otherwise (Eligible, Reason) — Eligible here means "in scope for this store",
|
||||
/// not "this order's items satisfy the rule" (use EvaluateEligibilityAsync for that).
|
||||
/// </summary>
|
||||
public async Task<(bool Eligible, string? Reason)?> CheckStoreScopeEligibilityAsync(Guid storeId, Guid schemeId)
|
||||
{
|
||||
var store = await storeRepo.GetByIdWithRegionAsync(storeId);
|
||||
if (store is null || !store.IsActive) return null;
|
||||
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
var regionId = store.Route?.FK_RegionId;
|
||||
if (scheme.FK_RegionId.HasValue && scheme.FK_RegionId != regionId)
|
||||
return (false, "Scheme is not available in the store's region.");
|
||||
|
||||
if (!string.IsNullOrEmpty(scheme.EligibleSegment) &&
|
||||
!string.Equals(scheme.EligibleSegment, store.Segment, StringComparison.OrdinalIgnoreCase))
|
||||
return (false, $"Scheme is only available to the '{scheme.EligibleSegment}' segment.");
|
||||
|
||||
var today = DateTime.Now;
|
||||
if (today < scheme.DateRangeFrom || today > scheme.DateRangeTo)
|
||||
return (false, "Scheme is not currently active (outside its date range).");
|
||||
|
||||
return (true, null);
|
||||
}
|
||||
|
||||
private static SchemeEligibilityResponse EvaluateRule(Models.Scheme scheme, List<OrderItem> orderItems)
|
||||
{
|
||||
switch (scheme.RuleType)
|
||||
{
|
||||
case SchemeRuleType.BuyXGetY:
|
||||
{
|
||||
if (scheme.FK_TriggerItemId is null || scheme.TriggerQty is null or <= 0 ||
|
||||
scheme.FK_FreeItemId is null || scheme.FreeQty is null or <= 0)
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false,
|
||||
"Scheme has no free-goods rule configured.", null, null, null);
|
||||
|
||||
var boughtQty = orderItems.Where(i => i.FK_ItemId == scheme.FK_TriggerItemId).Sum(i => i.Quantity);
|
||||
if (boughtQty < scheme.TriggerQty)
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false,
|
||||
$"Requires {scheme.TriggerQty} of the trigger item; order has {boughtQty}.", null, null, null);
|
||||
|
||||
var multiplier = boughtQty / scheme.TriggerQty.Value;
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, true, null,
|
||||
null, scheme.FK_FreeItemId, scheme.FreeQty * multiplier);
|
||||
}
|
||||
case SchemeRuleType.FreeBundle:
|
||||
{
|
||||
if (scheme.BundleComponents.Count == 0 || scheme.FK_FreeItemId is null || scheme.FreeQty is null or <= 0)
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false,
|
||||
"Scheme has no bundle components or free-goods payout configured.", null, null, null);
|
||||
|
||||
var missing = scheme.BundleComponents
|
||||
.Where(c => orderItems.Where(i => i.FK_ItemId == c.FK_ItemId).Sum(i => i.Quantity) < c.Qty)
|
||||
.ToList();
|
||||
if (missing.Count > 0)
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false,
|
||||
"Order is missing required bundle components.", null, null, null);
|
||||
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, true, null,
|
||||
null, scheme.FK_FreeItemId, scheme.FreeQty);
|
||||
}
|
||||
case SchemeRuleType.FlatPercent:
|
||||
{
|
||||
if (string.IsNullOrEmpty(scheme.RuleConfig))
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false, "Scheme has no RuleConfig.", null, null, null);
|
||||
var cfg = JsonSerializer.Deserialize<FlatPercentConfig>(scheme.RuleConfig, JsonOptions)!;
|
||||
var orderTotal = orderItems.Sum(i => i.Quantity * i.UnitPrice);
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, true, null,
|
||||
Math.Round(orderTotal * cfg.DiscountPercent / 100m, 2), null, null);
|
||||
}
|
||||
case SchemeRuleType.SlabDiscount:
|
||||
{
|
||||
if (string.IsNullOrEmpty(scheme.RuleConfig))
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false, "Scheme has no RuleConfig.", null, null, null);
|
||||
var cfg = JsonSerializer.Deserialize<SlabDiscountConfig>(scheme.RuleConfig, JsonOptions)!;
|
||||
var orderTotal = orderItems.Sum(i => i.Quantity * i.UnitPrice);
|
||||
var tier = cfg.Tiers.Where(t => orderTotal >= t.MinOrderAmount)
|
||||
.OrderByDescending(t => t.MinOrderAmount).FirstOrDefault();
|
||||
if (tier is null)
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false,
|
||||
"Order total does not meet any slab threshold.", null, null, null);
|
||||
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, true, null,
|
||||
Math.Round(orderTotal * tier.DiscountPercent / 100m, 2), null, null);
|
||||
}
|
||||
default:
|
||||
return new SchemeEligibilityResponse(scheme.Id, scheme.Name, scheme.RuleType, false, "Unknown rule type.", null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
// ── applySchemeDiscount(orderId, schemeId) ───────────────────────────────
|
||||
|
||||
public async Task<SchemeRedemptionResponse?> ApplySchemeAsync(Guid orderId, Guid schemeId, CancellationToken ct = default)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null || !scheme.IsActive) return null;
|
||||
|
||||
var order = await orderRepo.GetByIdAsync(orderId);
|
||||
if (order is null || !order.IsActive) return null;
|
||||
|
||||
if (await repo.HasRedemptionAsync(schemeId, orderId))
|
||||
throw new InvalidOperationException("This scheme has already been redeemed against this order.");
|
||||
|
||||
var orderItems = await orderRepo.GetItemsByOrderIdAsync(orderId);
|
||||
var eligibility = EvaluateRule(scheme, orderItems);
|
||||
if (!eligibility.Eligible)
|
||||
throw new InvalidOperationException(eligibility.Reason ?? "Order is not eligible for this scheme.");
|
||||
|
||||
var redemption = new SchemeRedemption
|
||||
{
|
||||
FK_SchemeId = schemeId,
|
||||
FK_OrderId = orderId,
|
||||
DiscountAmount = eligibility.DiscountAmount
|
||||
};
|
||||
|
||||
var newOrderItems = new List<OrderItem>();
|
||||
|
||||
if (eligibility.FreeItemId.HasValue && eligibility.FreeQty is > 0)
|
||||
{
|
||||
var freeItem = await itemRepo.GetByIdAsync(eligibility.FreeItemId.Value)
|
||||
?? throw new InvalidOperationException("Free item not found.");
|
||||
|
||||
var availableQty = (await stockRepo.GetBalancesByItemAsync(freeItem.Id)).Sum(b => b.Quantity);
|
||||
if (availableQty < eligibility.FreeQty.Value)
|
||||
throw new InvalidOperationException($"Insufficient stock of '{freeItem.Sku}' to fulfil the free-goods scheme.");
|
||||
|
||||
newOrderItems.Add(new OrderItem
|
||||
{
|
||||
FK_OrderId = orderId,
|
||||
FK_ItemId = freeItem.Id,
|
||||
Quantity = (int)eligibility.FreeQty.Value,
|
||||
UnitPrice = 0m
|
||||
});
|
||||
|
||||
redemption.FK_FreeItemId = freeItem.Id;
|
||||
redemption.FreeQty = eligibility.FreeQty;
|
||||
redemption.FreeItemCostValue = freeItem.CostPrice ?? 0m;
|
||||
}
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (newOrderItems.Count > 0) await orderRepo.AddItemsAsync(newOrderItems);
|
||||
await repo.AddRedemptionAsync(redemption);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var reloaded = (await repo.GetRedemptionsAsync(schemeId)).First(r => r.Id == redemption.Id);
|
||||
return ToRedemptionResponse(reloaded);
|
||||
}
|
||||
|
||||
// ── trackSchemeSpend(schemeId) ───────────────────────────────────────────
|
||||
|
||||
public async Task<SchemeSpendResponse?> GetSpendAsync(Guid schemeId)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null) return null;
|
||||
|
||||
var redemptions = await repo.GetRedemptionsAsync(schemeId);
|
||||
var discountSpend = redemptions.Sum(r => r.DiscountAmount ?? 0m);
|
||||
var freeGoodsSpend = redemptions.Sum(r => (r.FreeItemCostValue ?? 0m) * (r.FreeQty ?? 0m));
|
||||
|
||||
return new SchemeSpendResponse(schemeId, discountSpend, freeGoodsSpend, discountSpend + freeGoodsSpend, redemptions.Count);
|
||||
}
|
||||
|
||||
// ── getSchemeROI(schemeId) ───────────────────────────────────────────────
|
||||
|
||||
public async Task<SchemeROIResponse?> GetROIAsync(Guid schemeId)
|
||||
{
|
||||
var scheme = await repo.GetByIdAsync(schemeId);
|
||||
if (scheme is null) return null;
|
||||
|
||||
var redemptions = await repo.GetRedemptionsAsync(schemeId);
|
||||
var spend = await GetSpendAsync(schemeId);
|
||||
|
||||
var actualSales = redemptions
|
||||
.Where(r => r.Order is not null)
|
||||
.Select(r => r.Order!)
|
||||
.Distinct()
|
||||
.Sum(o => o.TotalAmount);
|
||||
|
||||
var baseline = scheme.BaselineExpectedSales ?? 0m;
|
||||
var incremental = actualSales - baseline;
|
||||
decimal? roi = spend!.TotalSpend > 0 ? incremental / spend.TotalSpend : null;
|
||||
|
||||
return new SchemeROIResponse(schemeId, baseline, actualSales, incremental, spend.TotalSpend, roi);
|
||||
}
|
||||
|
||||
private async Task ValidateFreeGoodsRuleAsync(SchemeRuleType ruleType, Guid? triggerItemId, int? triggerQty, Guid? freeItemId, decimal? freeQty)
|
||||
{
|
||||
if (ruleType is not (SchemeRuleType.BuyXGetY or SchemeRuleType.FreeBundle))
|
||||
throw new InvalidOperationException($"Free-goods rule only applies to BuyXGetY or FreeBundle schemes, not '{ruleType}'.");
|
||||
|
||||
if (ruleType == SchemeRuleType.BuyXGetY)
|
||||
{
|
||||
if (triggerItemId is null || triggerQty is null or <= 0)
|
||||
throw new InvalidOperationException("BuyXGetY requires TriggerItemId and a positive TriggerQty.");
|
||||
if (await itemRepo.GetByIdAsync(triggerItemId.Value) is null)
|
||||
throw new InvalidOperationException("Trigger item not found.");
|
||||
}
|
||||
|
||||
if (freeItemId is null || freeQty is null or <= 0)
|
||||
throw new InvalidOperationException("FreeItemId and a positive FreeQty are required.");
|
||||
if (await itemRepo.GetByIdAsync(freeItemId.Value) is null)
|
||||
throw new InvalidOperationException("Free item not found.");
|
||||
}
|
||||
|
||||
private static void ValidatePercentRuleConfig(SchemeRuleType ruleType, string? ruleConfig)
|
||||
{
|
||||
if (ruleType is not (SchemeRuleType.SlabDiscount or SchemeRuleType.FlatPercent)) return;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(ruleConfig))
|
||||
throw new InvalidOperationException($"RuleConfig is required for RuleType '{ruleType}'.");
|
||||
|
||||
try
|
||||
{
|
||||
if (ruleType == SchemeRuleType.SlabDiscount)
|
||||
{
|
||||
var slab = JsonSerializer.Deserialize<SlabDiscountConfig>(ruleConfig, JsonOptions) ?? throw new JsonException();
|
||||
if (slab.Tiers.Count == 0)
|
||||
throw new InvalidOperationException("SlabDiscount scheme requires at least one tier.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_ = JsonSerializer.Deserialize<FlatPercentConfig>(ruleConfig, JsonOptions) ?? throw new JsonException();
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
throw new InvalidOperationException($"RuleConfig is not valid JSON for RuleType '{ruleType}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ public interface IStockRepository
|
||||
{
|
||||
// Balance
|
||||
Task<StockBalance?> GetBalanceAsync(Guid itemId, Guid locationId);
|
||||
Task<List<StockBalance>> GetBalancesByLocationAsync(Guid locationId, LocationType locationType);
|
||||
Task<List<StockBalance>> GetBalancesAsync(Guid? locationId, LocationType? locationType, Guid? itemId, int page, int pageSize);
|
||||
Task<int> GetBalancesCountAsync(Guid? locationId, LocationType? locationType, Guid? itemId);
|
||||
Task<List<StockBalance>> GetBalancesByItemAsync(Guid itemId);
|
||||
|
||||
@@ -11,6 +11,12 @@ public class StockRepository(AppDBContext db) : IStockRepository
|
||||
.Include(b => b.Item)
|
||||
.FirstOrDefaultAsync(b => b.FK_ItemId == itemId && b.LocationId == locationId);
|
||||
|
||||
public Task<List<StockBalance>> GetBalancesByLocationAsync(Guid locationId, LocationType locationType) =>
|
||||
db.StockBalances
|
||||
.Include(b => b.Item)
|
||||
.Where(b => b.LocationId == locationId && b.LocationType == locationType)
|
||||
.ToListAsync();
|
||||
|
||||
public Task<List<StockBalance>> GetBalancesAsync(Guid? locationId, LocationType? locationType, Guid? itemId, int page, int pageSize)
|
||||
{
|
||||
var query = db.StockBalances.Include(b => b.Item).AsQueryable();
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace Distribution.Features.Store;
|
||||
public interface IStoreRepository
|
||||
{
|
||||
Task<Models.Store?> GetByIdAsync(Guid id);
|
||||
Task<Models.Store?> GetByIdWithRegionAsync(Guid id);
|
||||
Task<List<Models.Store>> GetAllAsync();
|
||||
Task AddAsync(Models.Store entity);
|
||||
void Update(Models.Store entity);
|
||||
|
||||
@@ -8,6 +8,11 @@ public class StoreRepository(AppDBContext context) : IStoreRepository
|
||||
public async Task<Models.Store?> GetByIdAsync(Guid id) =>
|
||||
await context.Stores.FindAsync(id);
|
||||
|
||||
public async Task<Models.Store?> GetByIdWithRegionAsync(Guid id) =>
|
||||
await context.Stores
|
||||
.Include(s => s.Route).ThenInclude(r => r.Region)
|
||||
.FirstOrDefaultAsync(s => s.Id == id);
|
||||
|
||||
public async Task<List<Models.Store>> GetAllAsync() =>
|
||||
await context.Stores.ToListAsync();
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
using Distribution.Features.Scheme;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Store;
|
||||
|
||||
public class StoreService(IStoreRepository repo, IUnitOfWork uow, ICurrentUserService currentUser, IScopeAccessService scopeAccess)
|
||||
public class StoreService(IStoreRepository repo, IUnitOfWork uow, ICurrentUserService currentUser, IScopeAccessService scopeAccess, SchemeService schemeService)
|
||||
{
|
||||
private const int GlobalScopeRoleLevel = 50;
|
||||
private const int CreditApproverRoleLevel = 20;
|
||||
@@ -217,8 +218,10 @@ public class StoreService(IStoreRepository repo, IUnitOfWork uow, ICurrentUserSe
|
||||
var store = await repo.GetByIdAsync(id);
|
||||
if (store is null || !store.IsActive) return null;
|
||||
if (!await HasStoreScopeAsync(id)) return null;
|
||||
// Wired to Step 17 (Promotions & Schemes) once scheme rules exist.
|
||||
return new SchemeEligibilityResponse(true, null);
|
||||
|
||||
var result = await schemeService.CheckStoreScopeEligibilityAsync(id, schemeId);
|
||||
if (result is null) return null;
|
||||
return new SchemeEligibilityResponse(result.Value.Eligible, result.Value.Reason);
|
||||
}
|
||||
|
||||
public async Task<StoreDashboardResponse?> GetDashboardAsync(Guid id, string period)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Distribution.Features.Supplier;
|
||||
|
||||
public interface ISupplierRepository
|
||||
{
|
||||
Task<Models.Supplier?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.Supplier>> GetAllAsync();
|
||||
Task AddAsync(Models.Supplier entity);
|
||||
void Update(Models.Supplier entity);
|
||||
void Remove(Models.Supplier entity);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Supplier;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/suppliers")]
|
||||
[Authorize]
|
||||
public class SupplierController(SupplierService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(CreateSupplierRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateSupplierRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
return deleted ? NoContent() : NotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Distribution.Features.Supplier;
|
||||
|
||||
public record CreateSupplierRequest(string Name, string? ContactInfo);
|
||||
|
||||
public record UpdateSupplierRequest(string Name, string? ContactInfo);
|
||||
|
||||
public record SupplierResponse(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? ContactInfo,
|
||||
decimal? PerformanceScore,
|
||||
bool IsActive,
|
||||
DateTime CreatedAt);
|
||||
@@ -0,0 +1,25 @@
|
||||
using Distribution.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Distribution.Features.Supplier;
|
||||
|
||||
public class SupplierRepository(AppDBContext context) : ISupplierRepository
|
||||
{
|
||||
public async Task<Models.Supplier?> GetByIdAsync(Guid id) =>
|
||||
await context.Suppliers.FindAsync(id);
|
||||
|
||||
public async Task<List<Models.Supplier>> GetAllAsync() =>
|
||||
await context.Suppliers.Where(s => s.IsActive).ToListAsync();
|
||||
|
||||
public async Task AddAsync(Models.Supplier entity) =>
|
||||
await context.Suppliers.AddAsync(entity);
|
||||
|
||||
public void Update(Models.Supplier entity) =>
|
||||
context.Suppliers.Update(entity);
|
||||
|
||||
public void Remove(Models.Supplier entity)
|
||||
{
|
||||
entity.IsActive = false;
|
||||
context.Suppliers.Update(entity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.Supplier;
|
||||
|
||||
public class SupplierService(ISupplierRepository repo, IUnitOfWork uow)
|
||||
{
|
||||
private static SupplierResponse Map(Models.Supplier s) =>
|
||||
new(s.Id, s.Name, s.ContactInfo, s.PerformanceScore, s.IsActive, s.CreatedAt);
|
||||
|
||||
public async Task<List<SupplierResponse>> GetAllAsync() =>
|
||||
(await repo.GetAllAsync()).Select(Map).ToList();
|
||||
|
||||
public async Task<SupplierResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var supplier = await repo.GetByIdAsync(id);
|
||||
if (supplier is null || !supplier.IsActive) return null;
|
||||
return Map(supplier);
|
||||
}
|
||||
|
||||
public async Task<SupplierResponse> CreateAsync(CreateSupplierRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var supplier = new Models.Supplier
|
||||
{
|
||||
Name = request.Name,
|
||||
ContactInfo = request.ContactInfo
|
||||
};
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { await repo.AddAsync(supplier); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return Map(supplier);
|
||||
}
|
||||
|
||||
public async Task<SupplierResponse?> UpdateAsync(Guid id, UpdateSupplierRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var supplier = await repo.GetByIdAsync(id);
|
||||
if (supplier is null || !supplier.IsActive) return null;
|
||||
|
||||
supplier.Name = request.Name;
|
||||
supplier.ContactInfo = request.ContactInfo;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(supplier); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return Map(supplier);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var supplier = await repo.GetByIdAsync(id);
|
||||
if (supplier is null || !supplier.IsActive) return false;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Remove(supplier); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
-2338
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,716 +0,0 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
|
||||
|
||||
namespace Distribution.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddStoreCreditAndKyc : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000035"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000035"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000032"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000032"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000005") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000032"), new Guid("10000000-0000-0000-0000-000000000005") });
|
||||
|
||||
migrationBuilder.AddColumn<decimal>(
|
||||
name: "CreditLimit",
|
||||
table: "Stores",
|
||||
type: "decimal(65,30)",
|
||||
nullable: false,
|
||||
defaultValue: 0m);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "KycStatus",
|
||||
table: "Stores",
|
||||
type: "int",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
|
||||
migrationBuilder.AddColumn<decimal>(
|
||||
name: "OutstandingBalance",
|
||||
table: "Stores",
|
||||
type: "decimal(65,30)",
|
||||
nullable: false,
|
||||
defaultValue: 0m);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "Segment",
|
||||
table: "Stores",
|
||||
type: "longtext",
|
||||
nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "StoreKycDocuments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_StoreId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
DocumentType = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
FileReference = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
UploadedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_StoreKycDocuments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_StoreKycDocuments_Stores_FK_StoreId",
|
||||
column: x => x.FK_StoreId,
|
||||
principalTable: "Stores",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000017"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "stores.kyc.verify", "Verify or reject store KYC documents" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000018"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "stores.credit.update", "Update store credit limit and outstanding balance" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000019"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.view", "View warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000020"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.create", "Create warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000021"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.update", "Update warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000022"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.delete", "Delete warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000023"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.view", "View orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000024"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.create", "Create orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000025"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.update", "Update orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000026"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.delete", "Delete orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000027"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.view", "View users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000028"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.create", "Create users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000029"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.update", "Update users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000030"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.deactivate", "Deactivate users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000031"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.assign_role", "Assign a role to a user" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000032"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.assign_scope", "Assign region/route/store scope to a user" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000033"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.view", "View items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000034"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.create", "Create items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000035"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.update", "Update items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000036"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.delete", "Delete items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000037"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "categories.view", "View categories" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000038"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "categories.create", "Create categories and subcategories" });
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Permissions",
|
||||
columns: new[] { "Id", "Code", "CreatedAt", "Description", "IsActive" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ new Guid("20000000-0000-0000-0000-000000000039"), "categories.update", new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), "Update categories and subcategories", true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000040"), "categories.delete", new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), "Delete categories and subcategories", true }
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "RolePermissions",
|
||||
columns: new[] { "FK_PermissionId", "FK_RoleId", "CreatedAt", "Id", "IsActive" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ new Guid("20000000-0000-0000-0000-000000000024"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("c0739b84-50a2-0971-429b-02bab8354c51"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("c268a531-44eb-0f29-82ba-18394ac2dcb5"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000033"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("ddb2d04d-19b0-20b1-2639-b157d12a9eec"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000037"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("320ba3fb-666c-ce57-3e61-95c9824c4048"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000018"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("f2c14d55-d557-5cd2-a70a-4a6f58933436"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("1b126bb0-e582-3e84-4728-a7ab5628fe7b"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("f50b201c-6c8d-0df8-85ad-08cb137bc213"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000033"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("0f291826-e169-c06a-0735-bd06cbb2062d"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000037"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("10dd0249-ce04-c5d9-8f94-ccb348c1d979"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000018"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("d92d572f-f1bf-9e7d-1d4d-7c7b0d575c8e"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000019"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("f367f6f6-3d26-7a6c-888b-da1a240b59af"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("929950da-d51b-ad5d-c4e5-55175908fb43"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("a9a49749-f99d-3166-5d92-b7e380fcabb2"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000034"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("b17df3df-022c-c903-6ce0-e6423e648dc8"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000037"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("a41f94ba-c24d-93dc-9f25-c462df19785a"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000016"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("e0b27435-f505-43f5-7ed9-4711f2248495"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000018"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("5e10d61c-2d7a-3388-722f-45232d2cfb71"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000019"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("d8257363-d838-fe7e-57a5-51b626dbfc83"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("04ece77e-b36f-8ed0-4ef9-2f6962b6f9c6"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("bf2a2f96-04ed-905d-5a8a-9047d814aa3e"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000005"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("4d287b19-ba40-7d4d-3d39-291be64197f8"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000027"), new Guid("10000000-0000-0000-0000-000000000005"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("43a4c7b4-a50f-aa37-b147-a30636d9d65f"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000039"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("a66f3854-5a8f-95c2-cb1c-b2b2e67ee226"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000040"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("14bcecd1-b1a2-6da3-155a-233611484467"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000039"), new Guid("10000000-0000-0000-0000-000000000005"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("aeb29e0e-e819-1446-6cc6-1fb64b5ecc6b"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000040"), new Guid("10000000-0000-0000-0000-000000000005"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("e18a6eca-1009-bcc6-35e9-ead943c1649f"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000039"), new Guid("10000000-0000-0000-0000-000000000006"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("3f32cdac-6925-23f2-064e-8226d781d4a3"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000040"), new Guid("10000000-0000-0000-0000-000000000006"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("dc3dd9ff-b123-a8d4-dcea-b4f5f8ff171e"), true }
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_StoreKycDocuments_FK_StoreId",
|
||||
table: "StoreKycDocuments",
|
||||
column: "FK_StoreId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "StoreKycDocuments");
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000024"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000033"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000037"), new Guid("10000000-0000-0000-0000-000000000001") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000018"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000033"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000037"), new Guid("10000000-0000-0000-0000-000000000002") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000018"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000019"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000034"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000037"), new Guid("10000000-0000-0000-0000-000000000003") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000016"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000018"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000019"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000025"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000039"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000040"), new Guid("10000000-0000-0000-0000-000000000004") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000026"), new Guid("10000000-0000-0000-0000-000000000005") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000027"), new Guid("10000000-0000-0000-0000-000000000005") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000039"), new Guid("10000000-0000-0000-0000-000000000005") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000040"), new Guid("10000000-0000-0000-0000-000000000005") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000039"), new Guid("10000000-0000-0000-0000-000000000006") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "RolePermissions",
|
||||
keyColumns: new[] { "FK_PermissionId", "FK_RoleId" },
|
||||
keyValues: new object[] { new Guid("20000000-0000-0000-0000-000000000040"), new Guid("10000000-0000-0000-0000-000000000006") });
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000039"));
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000040"));
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CreditLimit",
|
||||
table: "Stores");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "KycStatus",
|
||||
table: "Stores");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "OutstandingBalance",
|
||||
table: "Stores");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "Segment",
|
||||
table: "Stores");
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000017"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.view", "View warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000018"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.create", "Create warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000019"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.update", "Update warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000020"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "warehouses.delete", "Delete warehouses" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000021"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.view", "View orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000022"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.create", "Create orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000023"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.update", "Update orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000024"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "orders.delete", "Delete orders" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000025"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.view", "View users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000026"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.create", "Create users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000027"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.update", "Update users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000028"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.deactivate", "Deactivate users" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000029"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.assign_role", "Assign a role to a user" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000030"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "users.assign_scope", "Assign region/route/store scope to a user" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000031"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.view", "View items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000032"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.create", "Create items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000033"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.update", "Update items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000034"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "items.delete", "Delete items, brands and UOMs" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000035"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "categories.view", "View categories" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000036"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "categories.create", "Create categories and subcategories" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000037"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "categories.update", "Update categories and subcategories" });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Permissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("20000000-0000-0000-0000-000000000038"),
|
||||
columns: new[] { "Code", "Description" },
|
||||
values: new object[] { "categories.delete", "Delete categories and subcategories" });
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "RolePermissions",
|
||||
columns: new[] { "FK_PermissionId", "FK_RoleId", "CreatedAt", "Id", "IsActive" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("85ef4e27-8643-9c43-71f6-da56f66a5c47"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("1e353909-d682-58f6-df5c-8e57fa2512c9"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("7596f703-c6ab-316c-7c80-3f4e3daa174e"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000035"), new Guid("10000000-0000-0000-0000-000000000001"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("aa120c36-488e-34ba-e10a-2ac45e46e119"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("e4648655-7267-141e-51fa-f7d5fe3d2356"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("d427b9ea-2c9b-d93e-0843-02dfa1ae8887"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("b7dee5e3-f329-95a5-75c1-d02c3e40e229"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000035"), new Guid("10000000-0000-0000-0000-000000000002"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("e5506b30-527d-08f9-6caa-8a45d3d02999"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("0dd5c943-3ace-0560-6fbc-54d8e37ce014"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("ca97fb3d-132c-d8a5-4ab8-f7b8fc60f5e5"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("7780d277-9597-84ff-1a1a-f63fc6b4d3cb"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000032"), new Guid("10000000-0000-0000-0000-000000000003"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("8083c659-9506-0bd9-b793-3d6148ce9192"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000021"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("5c00e972-a697-d71a-6545-1fd8618826cf"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000022"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("e9b6af8e-7947-7290-9c92-2d9b6239f395"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("a701da28-aa75-3c1d-abdb-4317404f8df6"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000032"), new Guid("10000000-0000-0000-0000-000000000004"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("2c025310-765f-7d07-ab9a-50524c13d1d3"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000031"), new Guid("10000000-0000-0000-0000-000000000005"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("69f93a29-1df1-7b20-9d5c-94c264f8c4b8"), true },
|
||||
{ new Guid("20000000-0000-0000-0000-000000000032"), new Guid("10000000-0000-0000-0000-000000000005"), new DateTime(2026, 8, 18, 0, 0, 0, 0, DateTimeKind.Unspecified), new Guid("070813f7-4053-2889-0d14-d0d5834208c2"), true }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
+1754
File diff suppressed because it is too large
Load Diff
+612
-251
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,19 +1,33 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class DeliveryRun : Template
|
||||
{
|
||||
public RideType RideType { get; set; }
|
||||
public RideStatus Status { get; set; } = RideStatus.Draft;
|
||||
|
||||
public Guid FK_VehicleId { get; set; }
|
||||
[ForeignKey("FK_VehicleId")]
|
||||
public Vehicle Vehicle { get; set; }
|
||||
//public Guid FK_DriverId { get; set; }
|
||||
//[ForeignKey("FK_DriverId")]
|
||||
//public Driver Driver { get; set; }
|
||||
public int Meterstart { get; set; }
|
||||
public int Meterend { get; set; }
|
||||
|
||||
public Guid FK_DriverProfileId { get; set; }
|
||||
[ForeignKey("FK_DriverProfileId")]
|
||||
public DriverProfile DriverProfile { get; set; }
|
||||
|
||||
public Guid FK_RouteId { get; set; }
|
||||
[ForeignKey("FK_RouteId")]
|
||||
public Route Route { get; set; }
|
||||
|
||||
public Guid FK_SourceWarehouseId { get; set; }
|
||||
[ForeignKey("FK_SourceWarehouseId")]
|
||||
public Warehouse SourceWarehouse { get; set; }
|
||||
|
||||
public int Meterstart { get; set; }
|
||||
public int Meterend { get; set; }
|
||||
|
||||
public DateTime? StartedAt { get; set; }
|
||||
public DateTime? ActivatedAt { get; set; }
|
||||
public DateTime? ClosedAt { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class DriverComplianceConfig
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
public bool EnforceLicenseExpiry { get; set; } = false;
|
||||
public bool EnforceMedicalClearance { get; set; } = false;
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||
public Guid UpdatedBy { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class DriverProfile : Template
|
||||
{
|
||||
public Guid FK_UserId { get; set; }
|
||||
[ForeignKey("FK_UserId")]
|
||||
public User User { get; set; }
|
||||
|
||||
public string LicenseNumber { get; set; }
|
||||
public DateTime LicenseExpiry { get; set; }
|
||||
public DateTime MedicalClearanceExpiry { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,24 @@ namespace Distribution.Models
|
||||
CustomerReturn,
|
||||
Transfer,
|
||||
Damage,
|
||||
Adjustment
|
||||
Adjustment,
|
||||
Load
|
||||
}
|
||||
|
||||
public enum LoadingSheetStatus
|
||||
{
|
||||
Pending,
|
||||
DispatchConfirmed,
|
||||
ReceiptConfirmed,
|
||||
DiscrepancyFlagged,
|
||||
Resolved
|
||||
}
|
||||
|
||||
public enum RideType { Delivery, Sale }
|
||||
|
||||
public enum RideStatus { Draft, Open, Active, CancelRequested, Cancelled, Closed }
|
||||
|
||||
public enum CancelRequestType { VehicleBreakdown, DriverUnavailable, RouteIssue, Other }
|
||||
|
||||
public enum CancelRequestStatus { Pending, Approved, Rejected }
|
||||
}
|
||||
|
||||
@@ -26,6 +26,9 @@ namespace Distribution.Models
|
||||
|
||||
public decimal? SalePrice { get; set; }
|
||||
|
||||
/// <summary>Cost/purchase price, used to value free-goods scheme redemptions for getSchemeROI.</summary>
|
||||
public decimal? CostPrice { get; set; }
|
||||
|
||||
public SyncSource SyncSource { get; set; } = SyncSource.Manual;
|
||||
public int? ExternalErpItemId { get; set; }
|
||||
public DateTime? LastSyncedAt { get; set; }
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class LoadingSheet : Template
|
||||
{
|
||||
public Guid FK_RideId { get; set; }
|
||||
[ForeignKey("FK_RideId")]
|
||||
public DeliveryRun Ride { get; set; }
|
||||
|
||||
public Guid FK_SourceWarehouseId { get; set; }
|
||||
[ForeignKey("FK_SourceWarehouseId")]
|
||||
public Warehouse SourceWarehouse { get; set; }
|
||||
|
||||
public LoadingSheetStatus Status { get; set; } = LoadingSheetStatus.Pending;
|
||||
|
||||
public DateTime? DispatchConfirmedAt { get; set; }
|
||||
public Guid? DispatchConfirmedBy { get; set; }
|
||||
public DateTime? ReceiptConfirmedAt { get; set; }
|
||||
public Guid? ReceiptConfirmedBy { get; set; }
|
||||
|
||||
public List<LoadingSheetItem> Items { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class LoadingSheetItem
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public Guid FK_LoadingSheetId { get; set; }
|
||||
[ForeignKey("FK_LoadingSheetId")]
|
||||
public LoadingSheet LoadingSheet { get; set; }
|
||||
|
||||
public Guid FK_ItemId { get; set; }
|
||||
[ForeignKey("FK_ItemId")]
|
||||
public Item Item { get; set; }
|
||||
|
||||
public decimal QuantityDispatched { get; set; }
|
||||
public decimal? QuantityReceived { get; set; }
|
||||
public decimal? QuantityResolved { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class PriceList : Template
|
||||
{
|
||||
public string Name { get; set; }
|
||||
|
||||
public Guid? FK_RegionId { get; set; }
|
||||
[ForeignKey("FK_RegionId")]
|
||||
public Region? Region { get; set; }
|
||||
|
||||
public DateTime EffectiveFrom { get; set; }
|
||||
public DateTime EffectiveTo { get; set; }
|
||||
|
||||
public ICollection<PriceListItem> Items { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class PriceListItem : Template
|
||||
{
|
||||
public Guid FK_PriceListId { get; set; }
|
||||
[ForeignKey("FK_PriceListId")]
|
||||
public PriceList PriceList { get; set; }
|
||||
|
||||
public Guid FK_ItemId { get; set; }
|
||||
[ForeignKey("FK_ItemId")]
|
||||
public Item Item { get; set; }
|
||||
|
||||
public decimal Price { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Floor price for negotiation. Null = no negotiation allowed, Price is fixed.
|
||||
/// Must be less than or equal to Price when set.
|
||||
/// </summary>
|
||||
public decimal? MinPrice { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class RideCancelRequest
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public Guid FK_RideId { get; set; }
|
||||
[ForeignKey("FK_RideId")]
|
||||
public DeliveryRun Ride { get; set; }
|
||||
|
||||
public CancelRequestType TypeCode { get; set; }
|
||||
public string Reason { get; set; }
|
||||
|
||||
public Guid RequestedBy { get; set; }
|
||||
public DateTime RequestedAt { get; set; } = DateTime.Now;
|
||||
|
||||
public CancelRequestStatus Status { get; set; } = CancelRequestStatus.Pending;
|
||||
public Guid? ApprovedBy { get; set; }
|
||||
public DateTime? ApprovedAt { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public enum SchemeRuleType
|
||||
{
|
||||
BuyXGetY,
|
||||
SlabDiscount,
|
||||
FlatPercent,
|
||||
FreeBundle
|
||||
}
|
||||
|
||||
public class Scheme : Template
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public SchemeRuleType RuleType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// JSON payload for percentage-based rules only (SlabDiscount tiers, FlatPercent). Free-goods
|
||||
/// rules (BuyXGetY / FreeBundle) are structured fields/child rows below, not JSON, so they can
|
||||
/// be managed through their own CRUD endpoints instead of a hand-edited blob.
|
||||
/// </summary>
|
||||
public string? RuleConfig { get; set; }
|
||||
|
||||
// ── BuyXGetY: trigger item/qty; shares FK_FreeItemId/FreeQty below as the payout. ──────────
|
||||
|
||||
public Guid? FK_TriggerItemId { get; set; }
|
||||
public Item? TriggerItem { get; set; }
|
||||
public int? TriggerQty { get; set; }
|
||||
|
||||
// ── Free-goods payout, used by both BuyXGetY and FreeBundle. ─────────────────────────────
|
||||
|
||||
public Guid? FK_FreeItemId { get; set; }
|
||||
public Item? FreeItem { get; set; }
|
||||
public decimal? FreeQty { get; set; }
|
||||
|
||||
/// <summary>Required component items for a FreeBundle scheme — managed via its own CRUD.</summary>
|
||||
public ICollection<SchemeBundleComponent> BundleComponents { get; set; } = [];
|
||||
|
||||
public Guid? FK_RegionId { get; set; }
|
||||
public Region? Region { get; set; }
|
||||
|
||||
/// <summary>Store segment this scheme applies to (Gold/Silver/Key Account/...); null = all segments.</summary>
|
||||
public string? EligibleSegment { get; set; }
|
||||
|
||||
public DateTime DateRangeFrom { get; set; }
|
||||
public DateTime DateRangeTo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// When true, this scheme's discount is exempt from the per-role discount ceiling in
|
||||
/// 08_sales_agent_controls.md and stacks on top of it unconditionally.
|
||||
/// </summary>
|
||||
public bool AgentLimitExempt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Manual baseline (expected sales with no scheme running) used by getSchemeROI. Per the
|
||||
/// open question in docs/17_promotions_schemes.md, this is entered at scheme creation
|
||||
/// rather than computed from a trailing-period average.
|
||||
/// </summary>
|
||||
public decimal? BaselineExpectedSales { get; set; }
|
||||
|
||||
public ICollection<SchemeRedemption> Redemptions { get; set; } = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
/// <summary>A required item+qty line of a FreeBundle scheme (e.g. "buy A + B, get C free").</summary>
|
||||
public class SchemeBundleComponent
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public Guid FK_SchemeId { get; set; }
|
||||
[ForeignKey("FK_SchemeId")]
|
||||
public Scheme Scheme { get; set; }
|
||||
|
||||
public Guid FK_ItemId { get; set; }
|
||||
[ForeignKey("FK_ItemId")]
|
||||
public Item Item { get; set; }
|
||||
|
||||
public int Qty { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class SchemeRedemption
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
public Guid FK_SchemeId { get; set; }
|
||||
[ForeignKey("FK_SchemeId")]
|
||||
public Scheme Scheme { get; set; }
|
||||
|
||||
public Guid? FK_OrderId { get; set; }
|
||||
[ForeignKey("FK_OrderId")]
|
||||
public Order? Order { get; set; }
|
||||
|
||||
/// <summary>Placeholder for the future field-invoice module — no FieldInvoice entity exists yet.</summary>
|
||||
public Guid? FieldInvoiceId { get; set; }
|
||||
|
||||
public decimal? DiscountAmount { get; set; }
|
||||
|
||||
public Guid? FK_FreeItemId { get; set; }
|
||||
[ForeignKey("FK_FreeItemId")]
|
||||
public Item? FreeItem { get; set; }
|
||||
|
||||
public decimal? FreeQty { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Cost price of the free item snapshotted at redemption time, so getSchemeROI stays
|
||||
/// accurate even after the item's cost price later changes.
|
||||
/// </summary>
|
||||
public decimal? FreeItemCostValue { get; set; }
|
||||
|
||||
public DateTime RedeemedAt { get; set; } = DateTime.Now;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class Supplier : Template
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string? ContactInfo { get; set; }
|
||||
public decimal? PerformanceScore { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
public string RegNumber { get; set; }
|
||||
public string NumberPlate { get; set; }
|
||||
public VehicleType Type { get; set; }
|
||||
|
||||
public Guid? DefaultWarehouseId { get; set; }
|
||||
}
|
||||
public enum VehicleType
|
||||
{
|
||||
|
||||
@@ -3,13 +3,20 @@ using Distribution.Data;
|
||||
using Distribution.Features.Auth;
|
||||
using Distribution.Features.Brand;
|
||||
using Distribution.Features.Category;
|
||||
using Distribution.Features.DriverComplianceConfig;
|
||||
using Distribution.Features.DriverProfile;
|
||||
using Distribution.Features.Item;
|
||||
using Distribution.Features.Order;
|
||||
using Distribution.Features.PriceList;
|
||||
using Distribution.Features.Region;
|
||||
using Distribution.Features.LoadingEvent;
|
||||
using Distribution.Features.Ride;
|
||||
using Distribution.Features.Role;
|
||||
using Distribution.Features.Route;
|
||||
using Distribution.Features.Scheme;
|
||||
using Distribution.Features.Store;
|
||||
using Distribution.Features.Store.Kyc;
|
||||
using Distribution.Features.Supplier;
|
||||
using Distribution.Features.Sync;
|
||||
using Distribution.Features.Uom;
|
||||
using Distribution.Features.User;
|
||||
@@ -47,7 +54,15 @@ builder.Services.AddScoped<IBrandRepository, BrandRepository>();
|
||||
builder.Services.AddScoped<IUomRepository, UomRepository>();
|
||||
builder.Services.AddScoped<IItemRepository, ItemRepository>();
|
||||
builder.Services.AddScoped<IStockRepository, StockRepository>();
|
||||
builder.Services.AddScoped<IDriverProfileRepository, DriverProfileRepository>();
|
||||
builder.Services.AddScoped<IDriverComplianceConfigRepository, DriverComplianceConfigRepository>();
|
||||
builder.Services.AddScoped<IRideRepository, RideRepository>();
|
||||
builder.Services.AddScoped<IRideCancelRequestRepository, RideCancelRequestRepository>();
|
||||
builder.Services.AddScoped<ILoadingSheetRepository, LoadingSheetRepository>();
|
||||
builder.Services.AddScoped<IStoreKycDocumentRepository, StoreKycDocumentRepository>();
|
||||
builder.Services.AddScoped<IPriceListRepository, PriceListRepository>();
|
||||
builder.Services.AddScoped<ISupplierRepository, SupplierRepository>();
|
||||
builder.Services.AddScoped<ISchemeRepository, SchemeRepository>();
|
||||
|
||||
builder.Services.AddScoped<RegionService>();
|
||||
builder.Services.AddScoped<RouteService>();
|
||||
@@ -65,6 +80,13 @@ builder.Services.AddScoped<ItemService>();
|
||||
builder.Services.AddScoped<SyncService>();
|
||||
builder.Services.AddScoped<StockService>();
|
||||
builder.Services.AddScoped<StoreKycDocumentService>();
|
||||
builder.Services.AddScoped<PriceListService>();
|
||||
builder.Services.AddScoped<SupplierService>();
|
||||
builder.Services.AddScoped<DriverProfileService>();
|
||||
builder.Services.AddScoped<DriverComplianceConfigService>();
|
||||
builder.Services.AddScoped<RideService>();
|
||||
builder.Services.AddScoped<LoadingSheetService>();
|
||||
builder.Services.AddScoped<SchemeService>();
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
|
||||
|
||||
@@ -1,82 +1,251 @@
|
||||
# 03 — Ride Lifecycle
|
||||
|
||||
**Status**: Not Started
|
||||
**Status**: Done
|
||||
**Depends On**: 02 — Stock Ledger
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Turn the currently-unused `DeliveryRun` model into a working ride: a session that turns a vehicle
|
||||
into a temporary warehouse. Covers `assignVehicleToRoute`, `assignDriverToVehicle`,
|
||||
`checkDriverCompliance` from [mainPlan.md §5](./mainPlan.md#5-vehicle--fleet-management)
|
||||
and `planDeliveryRoute` from §3.
|
||||
|
||||
---
|
||||
|
||||
## Background / Context
|
||||
|
||||
`Models/DeliveryRun.cs` exists (`FK_VehicleId`, `FK_RouteId`, `Meterstart`, `Meterend`) but has no
|
||||
repository, service, or controller — it is completely unwired today, per [mainPlan.md](./mainPlan.md)'s
|
||||
"Known Gaps" table. `FK_DriverId`/`Driver` navigation is commented out because no `Driver` entity
|
||||
exists yet (gap #10 in [00_existing_gaps.md](./00_existing_gaps.md)) — this step is blocked on that
|
||||
being resolved first if driver assignment is required at ride-open time.
|
||||
Turn the currently-unused `DeliveryRun` model into a fully working ride — a session that turns a
|
||||
vehicle into a temporary warehouse. Covers driver profile management, ride creation, state
|
||||
transitions, cancellation workflow, and the vehicle breakdown scenario.
|
||||
|
||||
---
|
||||
|
||||
## Data Model Changes
|
||||
|
||||
### Ride (extending DeliveryRun)
|
||||
### New Entity — DriverProfile
|
||||
|
||||
Add a `Status` field to `DeliveryRun` for the state machine below, and a `RideType` field
|
||||
(`Delivery` | `Sale`).
|
||||
Linked one-to-one with `User`. Holds compliance data only — no login or auth fields.
|
||||
|
||||
### Ride State Machine
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| Id | Guid | PK |
|
||||
| FK_UserId | Guid | FK → User (unique) |
|
||||
| LicenseNumber | string | |
|
||||
| LicenseExpiry | DateTime | |
|
||||
| MedicalClearanceExpiry | DateTime | |
|
||||
| IsActive | bool | Can be suspended without deleting |
|
||||
| CreatedAt | DateTime | |
|
||||
|
||||
`Draft → Open → Active → Closed`. A vehicle can only be on one `Open`/`Active` ride at a time —
|
||||
enforced in the service layer, not the database.
|
||||
No license class tied to vehicle type — not required.
|
||||
|
||||
### Ride Type (Delivery vs Sale)
|
||||
**Compliance check rule:** Driver is compliant if `IsActive = true`, plus any checks that are enabled in `DriverComplianceConfig`. By default all checks are disabled. When enabled: `LicenseExpiry > today` AND/OR `MedicalClearanceExpiry > today`.
|
||||
|
||||
`Delivery` rides fulfill pre-confirmed orders (see [05_delivery_ride.md](./05_delivery_ride.md));
|
||||
`Sale` rides create invoices on the spot with no pre-orders (see [06_sale_ride.md](./06_sale_ride.md)).
|
||||
Both share the same ride lifecycle and loading event.
|
||||
---
|
||||
|
||||
### Updated Entity — Vehicle
|
||||
|
||||
Add one nullable field:
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| FK_DefaultWarehouseId | Guid? | If set, ride always loads from this warehouse. If null, warehouse is selected at ride creation. |
|
||||
|
||||
---
|
||||
|
||||
### Updated Entity — DeliveryRun (becomes Ride)
|
||||
|
||||
Add the following fields to the existing `DeliveryRun`:
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| RideType | RideType | Delivery or Sale |
|
||||
| Status | RideStatus | State machine below |
|
||||
| FK_DriverProfileId | Guid | FK → DriverProfile |
|
||||
| FK_SourceWarehouseId | Guid | Where stock is loaded from. Must be the same warehouse stock returns to on cancel/close. |
|
||||
| StartedAt | DateTime? | Set when Draft → Open |
|
||||
| ActivatedAt | DateTime? | Set when Open → Active |
|
||||
| ClosedAt | DateTime? | Set when Active → Closed |
|
||||
|
||||
---
|
||||
|
||||
### New Enum — RideType
|
||||
|
||||
```csharp
|
||||
public enum RideType { Delivery, Sale }
|
||||
```
|
||||
|
||||
### New Enum — RideStatus
|
||||
|
||||
```csharp
|
||||
public enum RideStatus { Draft, Open, Active, CancelRequested, Cancelled, Closed }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### New Entity — RideCancelRequest
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| Id | Guid | PK |
|
||||
| FK_RideId | Guid | FK → DeliveryRun |
|
||||
| TypeCode | CancelRequestType | Reason category |
|
||||
| Reason | string | Free text explanation |
|
||||
| RequestedBy | Guid | UserId |
|
||||
| RequestedAt | DateTime | |
|
||||
| Status | CancelRequestStatus | Pending, Approved, Rejected |
|
||||
| ApprovedBy | Guid? | UserId of approver |
|
||||
| ApprovedAt | DateTime? | |
|
||||
|
||||
### New Enum — CancelRequestType
|
||||
|
||||
```csharp
|
||||
public enum CancelRequestType
|
||||
{
|
||||
VehicleBreakdown,
|
||||
DriverUnavailable,
|
||||
RouteIssue,
|
||||
Other
|
||||
}
|
||||
```
|
||||
|
||||
### New Entity — DriverComplianceConfig
|
||||
|
||||
Single-row configuration table. Controls which compliance checks are enforced at ride open time.
|
||||
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| Id | Guid | PK |
|
||||
| EnforceLicenseExpiry | bool | Default false. If true, ride open is blocked if driver license is expired. |
|
||||
| EnforceMedicalClearance | bool | Default false. If true, ride open is blocked if medical clearance is expired. |
|
||||
| UpdatedAt | DateTime | |
|
||||
| UpdatedBy | Guid | UserId of last person who changed the config. |
|
||||
|
||||
Managed via a dedicated config endpoint. Only one row ever exists.
|
||||
|
||||
---
|
||||
|
||||
### New Enum — CancelRequestStatus
|
||||
|
||||
```csharp
|
||||
public enum CancelRequestStatus { Pending, Approved, Rejected }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## State Machine
|
||||
|
||||
```
|
||||
Draft → Open → Active → Closed
|
||||
↘ CancelRequested → Cancelled
|
||||
```
|
||||
|
||||
| Transition | Trigger | What it does |
|
||||
|---|---|---|
|
||||
| Draft → Open | `POST /api/rides/{id}/open` | Validates driver compliance. Checks vehicle has no other Open/Active ride. Sets `StartedAt`. |
|
||||
| Open → Active | `POST /api/rides/{id}/activate` | Called by loading event confirmation (Step 04). Sets `ActivatedAt`. |
|
||||
| Active → Closed | `POST /api/rides/{id}/close` | Called after ride reconciliation (Step 07). All stock must be returned to source warehouse. Sets `ClosedAt`. |
|
||||
| Active → CancelRequested | `POST /api/rides/{id}/cancel-request` | Driver submits cancel request with type code and reason. Ride status changes to `CancelRequested`. |
|
||||
| CancelRequested → Cancelled | `POST /api/rides/cancel-requests/{id}/approve` | Supervisor approves. Ride status changes to `Cancelled`. All stock must return to source warehouse before cancel completes. |
|
||||
| CancelRequested → Active | `POST /api/rides/cancel-requests/{id}/reject` | Supervisor rejects. Ride returns to `Active`. |
|
||||
|
||||
**Order assignment window:** Orders can be assigned to a Delivery ride from Draft until the ride transitions to Open. No new orders after Open.
|
||||
|
||||
---
|
||||
|
||||
## Warehouse Configuration
|
||||
|
||||
Per vehicle. A vehicle either has `FK_DefaultWarehouseId` set (always loads from that warehouse)
|
||||
or it is null (warehouse is selected manually at ride creation time).
|
||||
|
||||
Loading and unloading warehouse are always the same — stock must return to its source warehouse
|
||||
before a ride can close or cancel.
|
||||
|
||||
---
|
||||
|
||||
## Vehicle Breakdown Scenario
|
||||
|
||||
1. Driver submits cancel request with `TypeCode = VehicleBreakdown`.
|
||||
2. Ride status moves to `CancelRequested`.
|
||||
3. Supervisor views a breakdown assist endpoint that lists all currently `Active` rides with their
|
||||
current vehicle stock levels and the stranded ride's open orders — supervisor decides manually
|
||||
which ride takes over which orders.
|
||||
4. Supervisor approves the cancel request.
|
||||
5. Ride moves to `Cancelled` once all stock is confirmed returned to source warehouse.
|
||||
|
||||
The system surfaces the information — it does not automatically reassign orders.
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Function reference | Endpoint intent |
|
||||
|---|---|
|
||||
| `assignVehicleToRoute(vehicleId, routeId)` (§5) | Implicit in `POST /api/rides` — a ride binds a vehicle to a route for its duration |
|
||||
| `assignDriverToVehicle(vehicleId, driverId)` (§5) | `PUT /api/rides/{id}/driver` — blocked on Driver entity, see gap #10 |
|
||||
| `checkDriverCompliance(driverId)` (§5) | Called internally before a ride can move `Draft → Open` |
|
||||
| `planDeliveryRoute(warehouseId, orderIds[])` (§3) | `POST /api/rides` (for `RideType = Delivery`) |
|
||||
| — | `POST /api/rides/{id}/open`, `POST /api/rides/{id}/close` — state transitions |
|
||||
Base route: `/api/rides`
|
||||
|
||||
| Method | Route | Description |
|
||||
|---|---|---|
|
||||
| POST | `/` | Create ride (Draft). If vehicle has default warehouse, pre-populate it. |
|
||||
| GET | `/` | List rides (paginated). Filter by status, type, driverProfileId, vehicleId. |
|
||||
| GET | `/{id}` | Get ride detail |
|
||||
| PUT | `/{id}/driver` | Assign or change driver profile |
|
||||
| POST | `/{id}/open` | Transition Draft → Open |
|
||||
| POST | `/{id}/activate` | Transition Open → Active (called by loading event) |
|
||||
| POST | `/{id}/close` | Transition Active → Closed (called by reconciliation) |
|
||||
| POST | `/{id}/cancel-request` | Submit cancel request (Active rides only) |
|
||||
| GET | `/cancel-requests` | List cancel requests (paginated). Filter by status. |
|
||||
| POST | `/cancel-requests/{id}/approve` | Approve cancel request |
|
||||
| POST | `/cancel-requests/{id}/reject` | Reject cancel request |
|
||||
| GET | `/breakdown-assist/{rideId}` | Lists active rides with stock + stranded ride's open orders |
|
||||
|
||||
### DriverComplianceConfig
|
||||
|
||||
Base route: `/api/driver-compliance-config`
|
||||
|
||||
| Method | Route | Description |
|
||||
|---|---|---|
|
||||
| GET | `/` | Get current config |
|
||||
| PUT | `/` | Update config flags |
|
||||
|
||||
---
|
||||
|
||||
### DriverProfile
|
||||
|
||||
Base route: `/api/driver-profiles`
|
||||
|
||||
| Method | Route | Description |
|
||||
|---|---|---|
|
||||
| POST | `/` | Create driver profile (links to a User) |
|
||||
| GET | `/` | List driver profiles (paginated) |
|
||||
| GET | `/{id}` | Get driver profile detail |
|
||||
| PUT | `/{id}` | Update compliance fields |
|
||||
| DELETE | `/{id}` | Soft deactivate |
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
- A ride cannot open without a compliant driver (once Driver entity exists) and a vehicle not
|
||||
already on an open ride.
|
||||
- Opening a ride creates the vehicle's stock ledger location (see [02_stock_ledger.md](./02_stock_ledger.md)).
|
||||
|
||||
---
|
||||
|
||||
## Fraud / Control Considerations
|
||||
|
||||
- `checkDriverCompliance` failures must block ride open, not just warn.
|
||||
1. A ride cannot transition Draft → Open if `IsActive = false` on the driver profile. If `EnforceLicenseExpiry = true`, also blocks if license is expired. If `EnforceMedicalClearance = true`, also blocks if medical clearance is expired.
|
||||
2. A vehicle cannot be on more than one Open or Active ride at a time.
|
||||
3. Orders can only be assigned to a Delivery ride while it is in Draft status.
|
||||
4. Loading and unloading warehouse must be the same — enforced at close/cancel.
|
||||
5. A CancelRequested ride cannot close or activate until the request is resolved.
|
||||
6. All cancel requests must have a TypeCode — free text reason alone is not sufficient.
|
||||
7. All list endpoints return paginated responses.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Is a `Driver` a new entity distinct from `User`, or is "driver" just a `User` with a specific
|
||||
`Role`? Affects whether gap #10 needs a new table or just a role addition.
|
||||
1. **Cancel request type codes** — ✅ Resolved. `VehicleBreakdown`, `DriverUnavailable`, `RouteIssue`, `Other`.
|
||||
2. **Breakdown assist endpoint** — ✅ Resolved. System shows info only, supervisor decides manually. No auto-reassignment.
|
||||
3. **Driver compliance** — ✅ Resolved. Checks are configurable via `DriverComplianceConfig`. `IsActive` is always enforced. License and medical checks are optional flags, default off.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
> Fill this section in during planning discussion before writing any code.
|
||||
**Build order:**
|
||||
1. ✅ Enums — `RideType`, `RideStatus`, `CancelRequestType`, `CancelRequestStatus` → added to `Models/Enums.cs`
|
||||
2. ✅ Entities — `DriverProfile`, `DriverComplianceConfig`, `RideCancelRequest` (new); updated `Vehicle` (+`FK_DefaultWarehouseId`), updated `DeliveryRun` (+`RideType`, `Status`, `FK_DriverProfileId`, `FK_SourceWarehouseId`, `StartedAt`, `ActivatedAt`, `ClosedAt`)
|
||||
3. ✅ `AppDBContext` — new DbSets + Fluent config
|
||||
4. ✅ Migrations — `RideLifecycle` (schema), `RidePermissions` (10 new permissions seeded across all roles)
|
||||
5. ✅ DTOs — `DriverProfileDTOs.cs`, `DriverComplianceConfigDTOs.cs`, `RideDTOs.cs`
|
||||
6. ✅ Repositories — `IDriverProfileRepository`, `IDriverComplianceConfigRepository`, `IRideRepository`, `IRideCancelRequestRepository`
|
||||
7. ✅ Services — `DriverProfileService`, `DriverComplianceConfigService`, `RideService`
|
||||
8. ✅ Controllers — `DriverProfileController`, `DriverComplianceConfigController`, `RideController`
|
||||
9. ✅ DI registration in `Program.cs`
|
||||
|
||||
**Feature folders:** `Features/Ride/`, `Features/DriverProfile/`, `Features/DriverComplianceConfig/`
|
||||
|
||||
**Pending:** Tests for the three new services.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 04 — Loading Event
|
||||
|
||||
**Status**: Not Started
|
||||
**Status**: Planning
|
||||
**Depends On**: 03 — Ride Lifecycle
|
||||
|
||||
---
|
||||
@@ -8,76 +8,191 @@
|
||||
## Goal
|
||||
|
||||
Move stock from a source warehouse onto an opened ride's vehicle, with two-party confirmation.
|
||||
Covers the dispatch half of [mainPlan.md §6](./mainPlan.md#6-warehouse-management):
|
||||
`generatePickList`, `confirmPicking`, `packOrder`, `buildDispatchLoad`, and `calculateLoadPlan`
|
||||
from §5.
|
||||
When loading is confirmed, the vehicle's stock ledger is credited and the ride transitions
|
||||
`Open → Active` automatically. This is the first place the stock movement model gets exercised
|
||||
end-to-end.
|
||||
|
||||
---
|
||||
|
||||
## Background / Context
|
||||
|
||||
This is the first place the [02_stock_ledger.md](./02_stock_ledger.md) movement model gets
|
||||
exercised end-to-end: a `Load` movement debits the warehouse and credits the vehicle location
|
||||
created when the ride opened ([03_ride_lifecycle.md](./03_ride_lifecycle.md)).
|
||||
A vehicle is just a location with `LocationType.Vehicle` in the stock ledger — the same math as
|
||||
a warehouse. When loading is confirmed, two stock movements are created per item:
|
||||
- **Debit** source warehouse: `-qty` at `LocationType.Warehouse`
|
||||
- **Credit** vehicle: `+qty` at `LocationType.Vehicle`
|
||||
|
||||
From this point the vehicle carries live inventory that decreases with every sale or delivery
|
||||
(Steps 05/06) and must return to zero before the ride can close (Step 07).
|
||||
|
||||
---
|
||||
|
||||
## Data Model Changes
|
||||
|
||||
### Loading Sheet
|
||||
### New Entity — LoadingSheet
|
||||
|
||||
Header record: `RideId`, `SourceWarehouseId`, `Status` (`Pending`, `DispatchConfirmed`,
|
||||
`ReceiptConfirmed`, `DiscrepancyFlagged`, `Resolved`).
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| Id | Guid | PK |
|
||||
| FK_RideId | Guid | FK → DeliveryRun |
|
||||
| FK_SourceWarehouseId | Guid | FK → Warehouse |
|
||||
| Status | LoadingSheetStatus | State machine below |
|
||||
| DispatchConfirmedAt | DateTime? | Set when warehouse confirms dispatch |
|
||||
| DispatchConfirmedBy | Guid? | UserId of warehouse manager |
|
||||
| ReceiptConfirmedAt | DateTime? | Set when driver confirms receipt |
|
||||
| ReceiptConfirmedBy | Guid? | UserId of driver |
|
||||
| CreatedAt | DateTime | |
|
||||
|
||||
### Loading Line Item
|
||||
### New Entity — LoadingSheetItem
|
||||
|
||||
`LoadingSheetId`, `ItemId`, `QuantityDispatched` (set by warehouse manager), `QuantityReceived`
|
||||
(set by driver) — a mismatch between the two is a discrepancy.
|
||||
| Column | Type | Notes |
|
||||
|---|---|---|
|
||||
| Id | Guid | PK |
|
||||
| FK_LoadingSheetId | Guid | FK → LoadingSheet |
|
||||
| FK_ItemId | Guid | FK → Item |
|
||||
| QuantityDispatched | decimal | Set by warehouse manager at confirm-dispatch |
|
||||
| QuantityReceived | decimal? | Set by driver before confirm-receipt |
|
||||
| QuantityResolved | decimal? | Set by supervisor when resolving a discrepancy |
|
||||
|
||||
### Two-Party Confirmation
|
||||
### New Enum — LoadingSheetStatus
|
||||
|
||||
Warehouse manager confirms what was dispatched (`generatePickList` → `confirmPicking` →
|
||||
`packOrder`); driver separately confirms what was received onto the vehicle. Both confirmations are
|
||||
required before the ride can move `Open → Active`.
|
||||
```csharp
|
||||
public enum LoadingSheetStatus
|
||||
{
|
||||
Pending,
|
||||
DispatchConfirmed,
|
||||
ReceiptConfirmed,
|
||||
DiscrepancyFlagged,
|
||||
Resolved
|
||||
}
|
||||
```
|
||||
|
||||
No changes to existing entities. Vehicle capacity check is deferred to Step 13 (Fleet Management).
|
||||
|
||||
---
|
||||
|
||||
## State Machine
|
||||
|
||||
```
|
||||
Pending → DispatchConfirmed → ReceiptConfirmed (all lines match)
|
||||
↘ DiscrepancyFlagged → Resolved
|
||||
```
|
||||
|
||||
| Transition | Trigger | What it does |
|
||||
|---|---|---|
|
||||
| Pending → DispatchConfirmed | `POST /{id}/confirm-dispatch` | Warehouse manager locks in `QuantityDispatched` per line. Ride stays `Open`. |
|
||||
| DispatchConfirmed → ReceiptConfirmed | `POST /{id}/confirm-receipt` | Driver's received quantities all match dispatched. Creates stock movements. Auto-triggers ride `Open → Active`. |
|
||||
| DispatchConfirmed → DiscrepancyFlagged | `POST /{id}/confirm-receipt` | Any line mismatch. No stock movements created. Ride stays `Open`. |
|
||||
| DiscrepancyFlagged → Resolved | `POST /{id}/resolve` | Supervisor enters `QuantityResolved` per line. Creates stock movements using resolved quantities. Auto-triggers ride `Open → Active`. |
|
||||
|
||||
---
|
||||
|
||||
## Item Population by Ride Type
|
||||
|
||||
| Ride Type | How items are added to the sheet |
|
||||
|---|---|
|
||||
| Delivery | Auto-populated on sheet creation from the aggregate of all order lines assigned to the ride |
|
||||
| Sale | Manually entered by warehouse manager via `PUT /{id}/items` (no orders to derive from) |
|
||||
|
||||
For Delivery rides the warehouse manager reviews the pre-populated quantities and may adjust before confirming dispatch. `PUT /{id}/items` is still available to override if needed.
|
||||
|
||||
---
|
||||
|
||||
## Stock Movements
|
||||
|
||||
Created at `ReceiptConfirmed` or `Resolved`. One pair per line item:
|
||||
|
||||
- **Debit** warehouse: `-QuantityFinal` at `LocationType.Warehouse`, `FK_LocationId = SourceWarehouseId`
|
||||
- **Credit** vehicle: `+QuantityFinal` at `LocationType.Vehicle`, `FK_LocationId = VehicleId`
|
||||
|
||||
`QuantityFinal` = `QuantityReceived` on a clean confirmation, or `QuantityResolved` when a discrepancy was resolved.
|
||||
|
||||
Movement `Type` = `Load` (new `StockMovementType` value to add to enums).
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Function reference | Endpoint intent |
|
||||
|---|---|
|
||||
| `generatePickList(orderIds[])` (§6) | `POST /api/loading-sheets` |
|
||||
| `confirmPicking(pickListId, pickedItems[])` (§6) | `POST /api/loading-sheets/{id}/confirm-dispatch` |
|
||||
| `packOrder(orderId, packageDetails)` (§6) | `POST /api/loading-sheets/{id}/pack` |
|
||||
| `buildDispatchLoad(vehicleId, orderIds[])` (§6) | Groups multiple orders into one loading sheet |
|
||||
| `calculateLoadPlan(vehicleId, orderIds[])` (§5) | Validates total volume/weight against vehicle capacity before dispatch confirmation |
|
||||
| — | `POST /api/loading-sheets/{id}/confirm-receipt` — driver-side confirmation |
|
||||
Base route: `/api/loading-sheets`
|
||||
|
||||
| Method | Route | Who | Description |
|
||||
|---|---|---|---|
|
||||
| POST | `/` | Warehouse mgr | Create sheet for an Open ride. Delivery rides auto-populate items from orders. |
|
||||
| GET | `/` | Any | List sheets. Filter by `rideId`, `status`. Paginated. |
|
||||
| GET | `/{id}` | Any | Get sheet detail with all line items |
|
||||
| PUT | `/{id}/items` | Warehouse mgr | Set or override item quantities (required for Sale rides, optional for Delivery) |
|
||||
| POST | `/{id}/confirm-dispatch` | Warehouse mgr | Pending → DispatchConfirmed |
|
||||
| PUT | `/{id}/receipt-items` | Driver | Set `QuantityReceived` per line |
|
||||
| POST | `/{id}/confirm-receipt` | Driver | → ReceiptConfirmed or DiscrepancyFlagged |
|
||||
| POST | `/{id}/resolve` | Supervisor | Enter `QuantityResolved` per line → Resolved + ride activation |
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
- `QuantityDispatched != QuantityReceived` on any line flags the sheet `DiscrepancyFlagged` and
|
||||
blocks ride activation until resolved.
|
||||
- `calculateLoadPlan` must reject a load exceeding vehicle capacity before dispatch is confirmed,
|
||||
not after.
|
||||
1. A loading sheet can only be created for a ride in `Open` status.
|
||||
2. A ride can only have one active loading sheet (not `Resolved` or `ReceiptConfirmed`) at a time.
|
||||
3. `QuantityDispatched != QuantityReceived` on any line → `DiscrepancyFlagged`. No partial activation.
|
||||
4. Stock movements are created only once — at `ReceiptConfirmed` or `Resolved`. Never on dispatch.
|
||||
5. Discrepancies must be resolved per line item with an explicit `QuantityResolved` value. No bulk "accept driver" or "accept warehouse" shortcut.
|
||||
6. All list endpoints return paginated responses.
|
||||
7. Vehicle capacity check is not enforced in this step — deferred to Step 13.
|
||||
|
||||
---
|
||||
|
||||
## Permissions to Seed
|
||||
|
||||
| Code | Who |
|
||||
|---|---|
|
||||
| `loading.view` | All roles |
|
||||
| `loading.dispatch` | Warehouse manager and above |
|
||||
| `loading.receive` | Driver (AreaManager and above for testing) |
|
||||
| `loading.resolve` | Supervisor and above |
|
||||
|
||||
---
|
||||
|
||||
## Fraud / Control Considerations
|
||||
|
||||
- Discrepancies must be immediately visible, not silently averaged into stock adjustments — see
|
||||
[09_fraud_controls.md](./09_fraud_controls.md).
|
||||
- Discrepancies are immediately visible and block activation — they cannot be silently absorbed.
|
||||
- `QuantityResolved` is permanently stored per line for audit purposes, even after the sheet is resolved.
|
||||
- See [09_fraud_controls.md](./09_fraud_controls.md) for the audit trail layer that will sit on top of this.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Does `Vehicle` need a `Capacity` field added now (volume/weight), or is `calculateLoadPlan`
|
||||
deferred until that's available?
|
||||
- ✅ Vehicle capacity check — deferred to Step 13 (Fleet Management).
|
||||
- ✅ Discrepancy resolution — supervisor enters `QuantityResolved` per line item.
|
||||
- ✅ Ride activation trigger — `confirm-receipt` and `resolve` auto-trigger `Open → Active` internally.
|
||||
- ✅ Item population — Delivery rides auto-populated from orders; Sale rides manually entered.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
> Fill this section in during planning discussion before writing any code.
|
||||
**Build order:**
|
||||
1. Enum — add `LoadingSheetStatus` to `Models/Enums.cs`; add `Load` to `StockMovementType`
|
||||
2. Entities — `LoadingSheet`, `LoadingSheetItem` (new)
|
||||
3. `AppDBContext` — new DbSets + Fluent config
|
||||
4. Migration — `LoadingEvent` (schema) + `LoadingPermissions` (4 new permissions seeded)
|
||||
5. DTOs — `LoadingSheetDTOs.cs`
|
||||
6. Repository — `ILoadingSheetRepository`, `LoadingSheetRepository`
|
||||
7. Service — `LoadingSheetService`
|
||||
8. Controller — `LoadingSheetController`
|
||||
9. DI registration in `Program.cs`
|
||||
|
||||
**Feature folder:** `Features/LoadingEvent/`
|
||||
|
||||
**What was built:**
|
||||
1. ✅ Enums — added `LoadingSheetStatus` and `Load` to `MovementType` in `Models/Enums.cs`
|
||||
2. ✅ Entities — `LoadingSheet`, `LoadingSheetItem` created in `Models/`
|
||||
3. ✅ `AppDBContext` — `LoadingSheets`, `LoadingSheetItems` DbSets added; Fluent config for FK restrictions and ride/warehouse relationships
|
||||
4. ✅ DTOs — `LoadingSheetDTOs.cs` in `Features/LoadingEvent/`
|
||||
5. ✅ Repository — `ILoadingSheetRepository`, `LoadingSheetRepository` in `Features/LoadingEvent/`
|
||||
6. ✅ Service — `LoadingSheetService` in `Features/LoadingEvent/`
|
||||
7. ✅ Controller — `LoadingSheetController` in `Features/LoadingEvent/`
|
||||
8. ✅ DI registration in `Program.cs`
|
||||
9. ⚠️ Permissions added to seed (`loading.view`, `loading.dispatch`, `loading.receive`, `loading.resolve`) — **authorization layer is being replaced, skip this**
|
||||
|
||||
**Pending (run manually):**
|
||||
- `dotnet ef migrations add LoadingEvent` — blocked by a pre-existing duplicate Permission seed ID in `AppDBContextModelSnapshot.cs` (ID `20000000-0000-0000-0000-000000000040` is assigned to both `categories.delete` and `driver_profiles.create`). This is a snapshot consistency issue from a previous session and needs to be resolved before migration generation will succeed.
|
||||
- `dotnet ef database update` after migration is generated.
|
||||
|
||||
@@ -21,12 +21,18 @@ gap #8 in [00_existing_gaps.md](./00_existing_gaps.md). Credit fields exist info
|
||||
`OneTimeAmount` / `CreditAmount`, which stay as-is; this step adds the real credit-limit +
|
||||
outstanding-balance + KYC-gated-ordering flow on top.
|
||||
|
||||
`getStoreVisitHistory` and `checkStoreSchemeEligibility` are read-only integration points into
|
||||
modules that don't exist yet ([11_route_sales_management.md](./11_route_sales_management.md) for
|
||||
visits, [17_promotions_schemes.md](./17_promotions_schemes.md) for schemes). Implement them now
|
||||
with the query shape defined below; wire the actual join once those modules land — return an empty
|
||||
list / `eligible: true` (no active schemes to check) until then, guarded by a `NotImplementedYet`
|
||||
style short-circuit, not a broken query.
|
||||
`getStoreVisitHistory` and `checkStoreSchemeEligibility` were originally read-only integration
|
||||
points into modules that didn't exist yet ([11_route_sales_management.md](./11_route_sales_management.md)
|
||||
for visits, [17_promotions_schemes.md](./17_promotions_schemes.md) for schemes) — both shipped as
|
||||
placeholders (empty list / `eligible: true`) guarded by a `NotImplementedYet`-style short-circuit.
|
||||
|
||||
**Update (2026-08-21, after 17_promotions_schemes.md landed):** `checkStoreSchemeEligibility` is now
|
||||
wired for real. `StoreService.CheckSchemeEligibilityAsync` calls
|
||||
`SchemeService.CheckStoreScopeEligibilityAsync(storeId, schemeId)`, which checks the scheme's
|
||||
region/segment/date-range scope against the store (no order context, since this endpoint takes no
|
||||
`orderId` — that's a *scope* eligibility check, not the full order-line rule evaluation that
|
||||
`GET /api/schemes/eligible?storeId=...&orderId=...` does). `getStoreVisitHistory` is still an empty
|
||||
list — [11_route_sales_management.md](./11_route_sales_management.md) remains Not Started.
|
||||
|
||||
---
|
||||
|
||||
@@ -102,7 +108,7 @@ One migration needed:
|
||||
| GET | /api/stores/{id}/outstanding-balance | stores.view | Returns cached value + CreditLimit + available credit |
|
||||
| PUT | /api/stores/{id}/segment | stores.update | Body: `{ "segment": "Gold" }` |
|
||||
| GET | /api/stores/{id}/visit-history | stores.view | Paginated. Empty list until Step 11 wiring lands |
|
||||
| GET | /api/stores/{id}/schemes/{schemeId}/eligibility | stores.view | Returns `{ eligible: true, reason: null }` until Step 17 wiring lands |
|
||||
| GET | /api/stores/{id}/schemes/{schemeId}/eligibility | stores.view | Wired to Step 17 — returns real region/segment/date-range eligibility for the store against that scheme |
|
||||
| GET | /api/stores/{id}/dashboard?period=... | stores.view | Aggregates order count/value for the period from existing Order tables |
|
||||
|
||||
---
|
||||
@@ -206,7 +212,9 @@ Features/
|
||||
StoreController.cs (extended — credit-limit, balance, kyc/verify, segment,
|
||||
visit-history, scheme-eligibility, dashboard endpoints)
|
||||
StoreDTOs.cs (extended — new request/response records)
|
||||
StoreService.cs (extended — new methods, RoleLevel >= 20 credit-approver check)
|
||||
StoreService.cs (extended — new methods, RoleLevel >= 20 credit-approver check;
|
||||
CheckSchemeEligibilityAsync now depends on Features/Scheme's
|
||||
SchemeService for the real region/segment/date-range check)
|
||||
IStoreRepository.cs (extended — GetOrdersForDashboardAsync)
|
||||
StoreRepository.cs (extended)
|
||||
Kyc/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 14 — Pricing & Supplier Master Data
|
||||
|
||||
**Status**: Not Started
|
||||
**Depends On**: 01 — Item Catalog
|
||||
**Status**: Done — migration applied to the database
|
||||
**Depends On**: 01 — Item Catalog (Done)
|
||||
|
||||
---
|
||||
|
||||
@@ -15,56 +15,339 @@ records. `createProduct`/`deactivateSku` live in 01; this step is everything els
|
||||
|
||||
## Background / Context
|
||||
|
||||
`Item.BasePrice` (from [01_item_catalog.md](./01_item_catalog.md)) is a single flat price. There is
|
||||
no concept of a region- or date-scoped price list, and no `Supplier` entity anywhere in the schema.
|
||||
`Item.SalePrice` (from [01_item_catalog.md](./01_item_catalog.md)) is a single flat, optional price
|
||||
— `OrderItem.UnitPrice` is captured from it at order-creation time, or supplied manually if
|
||||
`SalePrice` is null. There is no concept of a region- or date-scoped price list, and no `Supplier`
|
||||
entity anywhere in the schema.
|
||||
|
||||
`applyPricingAndDiscounts` ([mainPlan.md §1](./mainPlan.md#1-order-management-lifecycle)) is the
|
||||
function that resolves the actual price for an order line; this step implements the price-list half
|
||||
of it (region + date scoping). The discount/scheme half stays out of scope until
|
||||
[17_promotions_schemes.md](./17_promotions_schemes.md) lands — until then `applyPricingAndDiscounts`
|
||||
only walks price lists, never scheme discounts.
|
||||
|
||||
Resolved in planning discussion (2026-08-20): price lists are **region-only in v1**, not
|
||||
segment-scoped. `Store.Segment` ([12_store_management.md](./12_store_management.md)) is not
|
||||
consulted by pricing. Segment-based pricing can be added as a later step without breaking this
|
||||
model, since it would only add an optional new scoping column.
|
||||
|
||||
### Negotiable price range (Min/Max)
|
||||
|
||||
An item's price within a price list can float in a band instead of being fixed: the same actor who
|
||||
creates the price list (`pricing.create`/`pricing.update`, AreaManager and above) sets both a
|
||||
**ceiling** (`Price` — the list/default price) and an optional **floor** (`MinPrice`) below which no
|
||||
order for that item may be priced. The sales rep/driver placing the order can then supply any
|
||||
`UnitPrice` within `[MinPrice, Price]` on `OrderItemRequest` instead of always taking the resolved
|
||||
default — the same negotiation-boundary pattern already used for discount limits in
|
||||
[08_sales_agent_controls.md](./08_sales_agent_controls.md).
|
||||
|
||||
- `PriceListItem.MinPrice (decimal?)` — `null` = no negotiation, the item is fixed at `Price`.
|
||||
- `PUT /api/price-lists/{id}/items/{sku}` accepts `{ "price": ..., "minPrice": ... }`; rejected with
|
||||
409 if `MinPrice > Price`.
|
||||
- `OrderService.CreateAsync` validates any caller-supplied `OrderItemRequest.UnitPrice` against
|
||||
`[MinPrice ?? Price, Price]` for that item's resolved price (region-scoped list → global list;
|
||||
the `Item.SalePrice` fallback has no `MinPrice` and is always fixed). The order is rejected
|
||||
(400, via a null resolution) if the requested price falls outside the band, or if no price can be
|
||||
resolved at all.
|
||||
|
||||
---
|
||||
|
||||
## Data Model Changes
|
||||
|
||||
### Price List
|
||||
### PriceList
|
||||
```
|
||||
PriceList
|
||||
├── Id (Guid) — PK, from Template
|
||||
├── Name (string)
|
||||
├── FK_RegionId (Guid?) — nullable, null = global (applies to all regions)
|
||||
├── EffectiveFrom (DateTime)
|
||||
├── EffectiveTo (DateTime)
|
||||
├── IsActive, CreatedAt — from Template
|
||||
```
|
||||
|
||||
`Name`, `RegionId` (nullable — null means global), `EffectiveFrom`, `EffectiveTo`.
|
||||
|
||||
### Price List Item
|
||||
|
||||
`PriceListId`, `ItemId`, `Price` — overrides `Item.BasePrice` when an applicable, currently-
|
||||
effective price list exists for the order's region.
|
||||
### PriceListItem
|
||||
```
|
||||
PriceListItem
|
||||
├── Id (Guid) — PK, from Template
|
||||
├── FK_PriceListId (Guid) — required
|
||||
├── FK_ItemId (Guid) — required
|
||||
├── Price (decimal) — ceiling/list price, overrides Item.SalePrice for this item while
|
||||
│ the parent PriceList is active and applicable to the order's region
|
||||
├── MinPrice (decimal?) — nullable floor for negotiated pricing; null = Price is fixed.
|
||||
│ Must be <= Price when set.
|
||||
├── IsActive, CreatedAt — from Template
|
||||
```
|
||||
Unique constraint on `(PriceListId, ItemId)` — one price per item per price list.
|
||||
|
||||
### Supplier
|
||||
```
|
||||
Supplier
|
||||
├── Id (Guid) — PK, from Template
|
||||
├── Name (string)
|
||||
├── ContactInfo (string?) — free text (phone/email/address), matches ContactInfo pattern
|
||||
│ used elsewhere rather than splitting into separate columns
|
||||
├── PerformanceScore (decimal?) — nullable, populated by 15_procurement.md's evaluateSupplier;
|
||||
│ this step only defines the column and leaves it null-only
|
||||
├── IsActive, CreatedAt — from Template
|
||||
```
|
||||
|
||||
`Name`, `ContactInfo`, `PerformanceScore` (nullable, populated by
|
||||
[15_procurement.md](./15_procurement.md)'s `evaluateSupplier`).
|
||||
---
|
||||
|
||||
## Migrations
|
||||
|
||||
One migration needed:
|
||||
1. **AddPricingAndSuppliers** — creates `PriceLists`, `PriceListItems`, `Suppliers` tables.
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Function reference | Endpoint intent |
|
||||
|---|---|
|
||||
| `createPriceList(name, region, effectiveDates)` | `POST /api/price-lists` |
|
||||
| `updateProductPricing(sku, priceListId, price)` | `PUT /api/price-lists/{id}/items/{sku}` |
|
||||
| `createSupplierMaster(supplierData)` | `POST /api/suppliers` |
|
||||
> Permission column names the target policy for each route; enforcement is **not implemented yet**
|
||||
> — see [Permissions to Add to Seed](#permissions-to-add-to-seed). Endpoints require
|
||||
> authentication only until seeding is turned on.
|
||||
|
||||
### Price Lists
|
||||
| Method | Route | Permission | Notes |
|
||||
|---|---|---|---|
|
||||
| GET | /api/price-lists | pricing.view | Filterable by region, active-on-date |
|
||||
| GET | /api/price-lists/{id} | pricing.view | Includes items |
|
||||
| POST | /api/price-lists | pricing.create | `createPriceList(name, region, effectiveDates)` |
|
||||
| PUT | /api/price-lists/{id} | pricing.update | Rejects if new dates overlap another price list for any shared `(ItemId, RegionId)` pair |
|
||||
| DELETE | /api/price-lists/{id} | pricing.delete | Soft delete |
|
||||
| PUT | /api/price-lists/{id}/items/{sku} | pricing.update | `updateProductPricing(sku, priceListId, price)` — upserts the `PriceListItem` row |
|
||||
| DELETE | /api/price-lists/{id}/items/{sku} | pricing.update | Removes an item's override from the price list |
|
||||
|
||||
### Suppliers
|
||||
| Method | Route | Permission | Notes |
|
||||
|---|---|---|---|
|
||||
| GET | /api/suppliers | suppliers.view | |
|
||||
| GET | /api/suppliers/{id} | suppliers.view | |
|
||||
| POST | /api/suppliers | suppliers.create | `createSupplierMaster(supplierData)` |
|
||||
| PUT | /api/suppliers/{id} | suppliers.update | Cannot set `PerformanceScore` directly — that field is read-only via this endpoint, only 15_procurement.md's `evaluateSupplier` writes it |
|
||||
| DELETE | /api/suppliers/{id} | suppliers.delete | Soft delete, blocked if any PurchaseOrder references it (enforced once 15_procurement.md exists; no-op check until then) |
|
||||
|
||||
---
|
||||
|
||||
## Request / Response Shapes
|
||||
|
||||
### POST `/api/price-lists`
|
||||
```json
|
||||
{ "name": "North Region Q3", "regionId": "...", "effectiveFrom": "2026-09-01", "effectiveTo": "2026-09-30" }
|
||||
```
|
||||
`regionId` omitted or null = global price list.
|
||||
|
||||
### PUT `/api/price-lists/{id}/items/{sku}`
|
||||
```json
|
||||
{ "price": 125.50, "minPrice": 115.00 }
|
||||
```
|
||||
Resolves `sku` to `ItemId`, upserts the `PriceListItem` row. `minPrice` is optional — omit or send
|
||||
`null` for a fixed, non-negotiable price. Rejected with 409 if `minPrice > price`.
|
||||
|
||||
### POST `/api/suppliers`
|
||||
```json
|
||||
{ "name": "Acme Distributors", "contactInfo": "acme@example.com, +91-98765-43210" }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
- `applyPricingAndDiscounts` (§1, used in [01_item_catalog.md](./01_item_catalog.md) and
|
||||
[06_sale_ride.md](./06_sale_ride.md)) resolves price in this order: region-scoped active price
|
||||
list → global active price list → `Item.BasePrice`.
|
||||
- Two price lists cannot have overlapping `EffectiveFrom`/`EffectiveTo` ranges for the same
|
||||
`(ItemId, RegionId)` pair.
|
||||
1. `applyPricingAndDiscounts` resolves the unit price for an order line in this order:
|
||||
region-scoped active price list → global active price list → `Item.SalePrice` → reject if all
|
||||
three are absent (order creation requires an explicit price, per rule 10 of
|
||||
[01_item_catalog.md](./01_item_catalog.md)).
|
||||
- "Active" means `EffectiveFrom <= orderDate <= EffectiveTo` and `IsActive = true`.
|
||||
- "Region-scoped" means `PriceList.RegionId` equals the order's store's region.
|
||||
- If more than one region-scoped price list is active for the same region (shouldn't happen
|
||||
given rule 2, but defensively), the most recently created one wins.
|
||||
2. Two active price lists cannot have overlapping `EffectiveFrom`/`EffectiveTo` ranges for the same
|
||||
`(ItemId, RegionId)` pair — checked at the `PriceListItem` level (a global list and a region list
|
||||
with the same item may coexist since region-scoped always wins in resolution, so the overlap
|
||||
check only compares price lists with the *same* `RegionId` value, including both being null).
|
||||
3. A `PriceList` cannot be deleted (soft delete) while any `PriceListItem` under it is still active
|
||||
— delete/deactivate the items first, or cascade-deactivate them in the same transaction (cascade
|
||||
chosen: deleting a price list deactivates all its `PriceListItem` rows in the same
|
||||
unit-of-work).
|
||||
4. `Supplier.PerformanceScore` is null until [15_procurement.md](./15_procurement.md)'s
|
||||
`evaluateSupplier` sets it; no endpoint in this step writes a non-null value.
|
||||
5. A `Supplier` cannot be hard-deleted, ever — soft delete only, matching the `Template.IsActive`
|
||||
convention used across the codebase.
|
||||
6. `PriceListItem.MinPrice`, when set, must be `<= Price` — enforced on every write via
|
||||
`PUT /api/price-lists/{id}/items/{sku}` (409 if violated).
|
||||
7. At order time, a caller-supplied `OrderItemRequest.UnitPrice` must fall within
|
||||
`[MinPrice ?? Price, Price]` for the item's resolved `PriceListItem` (region-scoped, then
|
||||
global). The `Item.SalePrice` fallback has no `MinPrice` — always fixed, no negotiation. An
|
||||
out-of-band price, or no resolvable price at all, rejects the whole order (400).
|
||||
|
||||
---
|
||||
|
||||
## Permissions to Add to Seed
|
||||
|
||||
**Status: Not implemented for now.** Endpoints in this step are built without permission
|
||||
enforcement (no `[Authorize(Policy = ...)]` gate) until explicitly requested. The codes and role
|
||||
assignments below are the target design to wire in later — keep them here as the reference, not as
|
||||
something to seed yet.
|
||||
|
||||
Target permission codes (not yet in `RoleAndPermissionSeed.cs`):
|
||||
```
|
||||
pricing.view, pricing.create, pricing.update, pricing.delete
|
||||
suppliers.view, suppliers.create, suppliers.update, suppliers.delete
|
||||
```
|
||||
|
||||
Target role assignments (mirrors the [01_item_catalog.md](./01_item_catalog.md) items/categories
|
||||
pattern), for when seeding is turned on:
|
||||
- **SalesRep (10)**: pricing.view
|
||||
- **Supervisor (20)**: pricing.view
|
||||
- **AreaManager (30)**: pricing.view, pricing.create, pricing.update, suppliers.view
|
||||
- **AreaSupervisor (40)**: all pricing + supplier permissions
|
||||
- **RegionalManager (50)**: all pricing + supplier permissions
|
||||
- **RegionalAgency (60)**: all pricing + supplier permissions
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Are price lists customer/segment-specific as well as region-specific (ties into `Store.Segment`
|
||||
from [12_store_management.md](./12_store_management.md)), or region-only in v1?
|
||||
- None. Resolved in planning discussion (2026-08-20): price lists are region-only in v1
|
||||
(no `Store.Segment` scoping); deleting a price list cascades to deactivate its items rather than
|
||||
being blocked by them.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
> Fill this section in during planning discussion before writing any code.
|
||||
### File structure created / touched
|
||||
```
|
||||
Features/
|
||||
PriceList/
|
||||
PriceListController.cs
|
||||
PriceListDTOs.cs
|
||||
PriceListService.cs (ResolveUnitPriceAsync — the price-list half of applyPricingAndDiscounts)
|
||||
IPriceListRepository.cs
|
||||
PriceListRepository.cs
|
||||
Supplier/
|
||||
SupplierController.cs
|
||||
SupplierDTOs.cs
|
||||
SupplierService.cs
|
||||
ISupplierRepository.cs
|
||||
SupplierRepository.cs
|
||||
Order/
|
||||
OrderDTOs.cs (extended — OrderItemRequest gained an optional UnitPrice override
|
||||
for the SalePrice-is-null / no-price-list-match case; OrderItemResponse
|
||||
now echoes the captured UnitPrice)
|
||||
OrderService.cs (extended — CreateAsync resolves each line's price via a private
|
||||
ResolveUnitPriceAsync that calls PriceListService, using the request's
|
||||
UnitPrice override if supplied; rejects the order (returns null) if no
|
||||
price can be resolved at all)
|
||||
Item/
|
||||
IItemRepository.cs / ItemRepository.cs (extended — GetBySkuAsync, needed to resolve the
|
||||
{sku} route segment on the price-list item endpoints)
|
||||
Store/
|
||||
IStoreRepository.cs / StoreRepository.cs (extended — GetByIdWithRegionAsync, includes
|
||||
Store.Route.Region so OrderService can read the
|
||||
store's RegionId for price resolution)
|
||||
|
||||
Models/
|
||||
PriceList.cs (new)
|
||||
PriceListItem.cs (new)
|
||||
Supplier.cs (new)
|
||||
|
||||
Data/AppDBContext.cs
|
||||
add PriceLists, PriceListItems, Suppliers DbSets; unique index on
|
||||
PriceListItem(FK_PriceListId, FK_ItemId)
|
||||
|
||||
Migrations/
|
||||
AddPricingAndSuppliers (applied)
|
||||
|
||||
Program.cs
|
||||
register IPriceListRepository/PriceListRepository, ISupplierRepository/SupplierRepository,
|
||||
PriceListService, SupplierService
|
||||
|
||||
Data/Seed/
|
||||
RoleAndPermissionSeed.cs — untouched. Permission enforcement is intentionally deferred (see
|
||||
Permissions to Add to Seed above); controllers use plain [Authorize]
|
||||
with no policy for now.
|
||||
```
|
||||
|
||||
### Price resolution logic (pseudo)
|
||||
```
|
||||
ResolveUnitPriceAsync(itemId, storeId, orderDate):
|
||||
regionId = store.RegionId
|
||||
regionList = active PriceListItem where ItemId = itemId
|
||||
and PriceList.RegionId = regionId
|
||||
and PriceList.EffectiveFrom <= orderDate <= PriceList.EffectiveTo
|
||||
and PriceList.IsActive and PriceListItem.IsActive
|
||||
order by PriceList.CreatedAt desc, take 1
|
||||
if regionList found: return regionList.Price
|
||||
|
||||
globalList = same query with PriceList.RegionId = null
|
||||
if globalList found: return globalList.Price
|
||||
|
||||
if item.SalePrice != null: return item.SalePrice
|
||||
return null // caller (OrderService) rejects with 400 if no explicit price was supplied
|
||||
```
|
||||
|
||||
### Overlap validation on price list write (pseudo)
|
||||
```
|
||||
On PUT /api/price-lists/{id}/items/{sku} or POST /api/price-lists:
|
||||
for each ItemId affected, check existing PriceListItem rows joined to PriceList
|
||||
where PriceList.RegionId = this.RegionId (both null counts as a match)
|
||||
and PriceList.Id != this.Id
|
||||
and date ranges overlap (existing.EffectiveFrom <= new.EffectiveTo
|
||||
and existing.EffectiveTo >= new.EffectiveFrom)
|
||||
→ reject with 400 if any match found
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Worked Example
|
||||
|
||||
Item `COKE-330` has `SalePrice = 100`. Store `S1` is in the North region.
|
||||
|
||||
**Set up a negotiable region price list:**
|
||||
```
|
||||
POST /api/price-lists
|
||||
{ "name": "North Region September", "regionId": "<northRegionId>",
|
||||
"effectiveFrom": "2026-09-01", "effectiveTo": "2026-09-30" }
|
||||
→ PriceList A (RegionId = North)
|
||||
|
||||
PUT /api/price-lists/{A.Id}/items/COKE-330
|
||||
{ "price": 90, "minPrice": 80 }
|
||||
```
|
||||
This publishes a band for `COKE-330` in the North region: ceiling 90, floor 80.
|
||||
|
||||
**Order at the default (no negotiation):**
|
||||
```
|
||||
POST /api/orders
|
||||
{ "storeId": "S1", "orderDate": "2026-09-15", "items": [{ "itemId": "COKE-330", "quantity": 10 }] }
|
||||
```
|
||||
No `unitPrice` supplied → resolves to the ceiling, **unit price = 90**.
|
||||
|
||||
**Order with a negotiated price inside the band:**
|
||||
```
|
||||
POST /api/orders
|
||||
{ "storeId": "S1", "orderDate": "2026-09-15",
|
||||
"items": [{ "itemId": "COKE-330", "quantity": 10, "unitPrice": 83 }] }
|
||||
```
|
||||
83 is within `[80, 90]` → **accepted, unit price = 83**.
|
||||
|
||||
**Order with a price outside the band:**
|
||||
```
|
||||
POST /api/orders
|
||||
{ "storeId": "S1", "orderDate": "2026-09-15",
|
||||
"items": [{ "itemId": "COKE-330", "quantity": 10, "unitPrice": 75 }] }
|
||||
```
|
||||
75 is below `MinPrice = 80` → **the whole order is rejected (400)**, same as if no price could be
|
||||
resolved at all.
|
||||
|
||||
A store in the South region (no region price list, so it falls through to the global list or
|
||||
`Item.SalePrice = 100`) has no `MinPrice` unless a global `PriceListItem` also sets one — an
|
||||
override there is rejected unless it equals the fixed price exactly.
|
||||
|
||||
**Supplier example** (unrelated to pricing resolution, same step):
|
||||
```
|
||||
POST /api/suppliers
|
||||
{ "name": "Acme Distributors", "contactInfo": "acme@example.com, +91-98765-43210" }
|
||||
→ Supplier { Id, Name: "Acme Distributors", PerformanceScore: null }
|
||||
```
|
||||
`PerformanceScore` stays null until [15_procurement.md](./15_procurement.md)'s `evaluateSupplier`
|
||||
runs against this supplier.
|
||||
|
||||
@@ -1,70 +1,378 @@
|
||||
# 17 — Promotions & Trade Scheme Management
|
||||
|
||||
**Status**: Not Started
|
||||
**Depends On**: 01 — Item Catalog, 14 — Pricing & Supplier Master Data
|
||||
**Status**: Done — migrations applied to the database
|
||||
**Depends On**: 01 — Item Catalog (Done), 14 — Pricing & Supplier Master Data (Done), 02 — Stock Ledger (Done)
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Covers [mainPlan.md §11](./mainPlan.md#11-promotions--trade-scheme-management)
|
||||
in full — an entirely new subsystem. Once built, `applyPricingAndDiscounts` (§1) and
|
||||
in full — an entirely new subsystem. `applyPricingAndDiscounts` (§1) and
|
||||
`checkStoreSchemeEligibility` (§4) both read from it.
|
||||
|
||||
---
|
||||
|
||||
## Background / Context
|
||||
|
||||
No scheme/promotion entity exists today. Every reference to "eligible discount" elsewhere in this
|
||||
doc set (order pricing, field invoices, agent discount limits) currently has no scheme data source
|
||||
— it only enforces the flat per-role discount ceiling from
|
||||
No scheme/promotion entity existed before this step. Every reference to "eligible discount"
|
||||
elsewhere in this doc set (order pricing, field invoices, agent discount limits) had no scheme data
|
||||
source — it only enforced the flat per-role discount ceiling from
|
||||
[08_sales_agent_controls.md](./08_sales_agent_controls.md).
|
||||
|
||||
For an enterprise distributor, free-goods/bundle promotions ("buy 10 get 1 free", "buy A + B get C
|
||||
free") are operationally different from discount schemes because they move physical stock at zero
|
||||
revenue, not just reduce a price. That distinction shaped the data model below: `BuyXGetY` and
|
||||
`FreeBundle` rules are structured columns/child rows (with their own CRUD), not a JSON blob, so a
|
||||
free-goods rule can be validated (item exists, positive qty, stock available) the same way any other
|
||||
order line is. `SlabDiscount`/`FlatPercent` stay JSON in `RuleConfig` since they're pure
|
||||
percentage-off rules with no inventory or fulfilment side effects.
|
||||
|
||||
---
|
||||
|
||||
## Data Model Changes
|
||||
|
||||
### Scheme
|
||||
```
|
||||
Scheme
|
||||
├── Id (Guid) — PK, from Template
|
||||
├── Name (string)
|
||||
├── RuleType (enum) — BuyXGetY, SlabDiscount, FlatPercent, FreeBundle
|
||||
├── RuleConfig (string?) — JSON, only used by SlabDiscount/FlatPercent (see below); null
|
||||
│ for BuyXGetY/FreeBundle
|
||||
├── FK_TriggerItemId (Guid?) — BuyXGetY only: the item the store must buy
|
||||
├── TriggerQty (int?) — BuyXGetY only: qty of TriggerItem required to earn one payout
|
||||
├── FK_FreeItemId (Guid?) — shared payout for BuyXGetY and FreeBundle: item given free
|
||||
├── FreeQty (decimal?) — shared payout: qty of FreeItem given free
|
||||
├── FK_RegionId (Guid?) — nullable, null = all regions
|
||||
├── EligibleSegment (string?) — Store.Segment match (Gold/Silver/Key Account/...); null = all segments
|
||||
├── DateRangeFrom (DateTime)
|
||||
├── DateRangeTo (DateTime)
|
||||
├── AgentLimitExempt (bool) — if true, this scheme's discount stacks on top of the per-role
|
||||
│ discount ceiling (08_sales_agent_controls.md) unconditionally
|
||||
├── BaselineExpectedSales (decimal?) — manual baseline used by getSchemeROI (see Open Questions)
|
||||
├── IsActive, CreatedAt — from Template
|
||||
```
|
||||
|
||||
`Name`, `RuleType` (`BuyXGetY`, `SlabDiscount`, `FlatPercent`), `RuleConfig` (JSON), `Eligibility`
|
||||
(store segment / region scope), `DateRangeFrom`, `DateRangeTo`.
|
||||
`RuleConfig` JSON shape (SlabDiscount/FlatPercent only):
|
||||
- `FlatPercent` — `{ "discountPercent": 10 }`
|
||||
- `SlabDiscount` — `{ "tiers": [{ "minOrderAmount": 5000, "discountPercent": 5 }, ...] }`, the
|
||||
highest tier whose `minOrderAmount` the order total meets or exceeds wins.
|
||||
|
||||
### Scheme Redemption
|
||||
### SchemeBundleComponent
|
||||
```
|
||||
SchemeBundleComponent
|
||||
├── Id (Guid) — PK
|
||||
├── FK_SchemeId (Guid) — required, cascade delete with parent Scheme
|
||||
├── FK_ItemId (Guid) — required
|
||||
├── Qty (int) — required qty of this item for the FreeBundle rule to trigger
|
||||
```
|
||||
Unique constraint on `(SchemeId, ItemId)`. Only meaningful when `Scheme.RuleType = FreeBundle` — the
|
||||
order must contain every component in at least its listed `Qty` before the scheme's
|
||||
`FK_FreeItemId`/`FreeQty` payout is granted.
|
||||
|
||||
`SchemeId`, `OrderId` (or `FieldInvoiceId`), `DiscountAmount`, `RedeemedAt` — feeds
|
||||
`trackSchemeSpend` and `getSchemeROI` without re-scanning every order.
|
||||
### SchemeRedemption
|
||||
```
|
||||
SchemeRedemption
|
||||
├── Id (Guid) — PK
|
||||
├── FK_SchemeId (Guid) — required
|
||||
├── FK_OrderId (Guid?) — nullable (see FieldInvoiceId below)
|
||||
├── FieldInvoiceId (Guid?) — placeholder for the future field-invoice module; no FieldInvoice
|
||||
│ entity exists yet, so this is an unconstrained Guid for now
|
||||
├── DiscountAmount (decimal?) — set for SlabDiscount/FlatPercent redemptions
|
||||
├── FK_FreeItemId (Guid?) — set for BuyXGetY/FreeBundle redemptions
|
||||
├── FreeQty (decimal?)
|
||||
├── FreeItemCostValue (decimal?) — free item's Item.CostPrice snapshotted at redemption time, so
|
||||
│ getSchemeROI/trackSchemeSpend stay accurate after CostPrice
|
||||
│ later changes
|
||||
├── RedeemedAt (DateTime)
|
||||
```
|
||||
At least one of `DiscountAmount` or `FreeQty` is set per redemption; `Scheme`/`Order` restrict-delete
|
||||
(a scheme or order with redemptions can't be hard-deleted, and soft-delete leaves history intact).
|
||||
|
||||
### Item (extended)
|
||||
```
|
||||
Item
|
||||
├── ...
|
||||
├── CostPrice (decimal?) — new: cost/purchase price, used to value free-goods redemptions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migrations
|
||||
|
||||
Two migrations:
|
||||
1. **AddPromotionsSchemes** (applied) — creates `Schemes`, `SchemeRedemptions`; adds `Item.CostPrice`.
|
||||
2. **AddSchemeFreeGoodsRuleAndBundleComponents** (applied) — makes `Scheme.RuleConfig` nullable, adds
|
||||
`Scheme.FK_TriggerItemId`/`TriggerQty`/`FK_FreeItemId`/`FreeQty`, creates `SchemeBundleComponents`.
|
||||
|
||||
(Split into two because the free-goods columns were promoted from a JSON blob to structured
|
||||
columns/child table after the first migration had already been applied to the dev database.)
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Function reference | Endpoint intent |
|
||||
|---|---|
|
||||
| `createScheme(schemeRules, eligibility, dateRange)` | `POST /api/schemes` |
|
||||
| `evaluateSchemeEligibility(storeId, orderId)` | `GET /api/schemes/eligible?storeId=...&orderId=...` |
|
||||
| `applySchemeDiscount(orderId, schemeId)` | `POST /api/orders/{id}/apply-scheme` |
|
||||
| `trackSchemeSpend(schemeId)` | `GET /api/schemes/{id}/spend` |
|
||||
| `getSchemeROI(schemeId)` | `GET /api/schemes/{id}/roi` |
|
||||
| Function reference | Endpoint | Notes |
|
||||
|---|---|---|
|
||||
| `createScheme(schemeRules, eligibility, dateRange)` | `POST /api/schemes` | `RuleConfig` required only for SlabDiscount/FlatPercent; `TriggerItemId`/`TriggerQty`/`FreeItemId`/`FreeQty`/`BundleComponents` can be supplied inline to fully create a BuyXGetY/FreeBundle scheme in one call |
|
||||
| — | `GET /api/schemes` | Filterable by region |
|
||||
| — | `GET /api/schemes/{id}` | Includes trigger/free item, bundle components |
|
||||
| — | `PUT /api/schemes/{id}` | Updates name/eligibility/date range/`RuleConfig` |
|
||||
| — | `DELETE /api/schemes/{id}` | Soft delete |
|
||||
| — | `PUT /api/schemes/{id}/free-goods-rule` | Sets the BuyXGetY trigger + shared free-goods payout (also the payout for FreeBundle) |
|
||||
| — | `DELETE /api/schemes/{id}/free-goods-rule` | Clears it |
|
||||
| — | `PUT /api/schemes/{id}/bundle-components/{itemId}` | Upserts one FreeBundle required-item row |
|
||||
| — | `DELETE /api/schemes/{id}/bundle-components/{itemId}` | Removes one FreeBundle required-item row |
|
||||
| `evaluateSchemeEligibility(storeId, orderId)` | `GET /api/schemes/eligible?storeId=...&orderId=...` | Returns eligibility for every in-scope scheme, not just one |
|
||||
| `applySchemeDiscount(orderId, schemeId)` | `POST /api/orders/{id}/apply-scheme` | Adds a zero-price order line for free-goods payouts |
|
||||
| `trackSchemeSpend(schemeId)` | `GET /api/schemes/{id}/spend` | Discount spend + free-goods cost spend |
|
||||
| `getSchemeROI(schemeId)` | `GET /api/schemes/{id}/roi` | Uses `BaselineExpectedSales` |
|
||||
|
||||
---
|
||||
|
||||
## Request / Response Shapes
|
||||
|
||||
### POST `/api/schemes` (BuyXGetY — created fully populated in one call)
|
||||
```json
|
||||
{
|
||||
"name": "Soap Buy10Get1",
|
||||
"ruleType": "BuyXGetY",
|
||||
"ruleConfig": null,
|
||||
"regionId": null,
|
||||
"eligibleSegment": "Gold",
|
||||
"dateRangeFrom": "2026-08-01T00:00:00",
|
||||
"dateRangeTo": "2026-08-31T23:59:59",
|
||||
"agentLimitExempt": false,
|
||||
"baselineExpectedSales": 50000,
|
||||
"triggerItemId": "<soapItemId>",
|
||||
"triggerQty": 10,
|
||||
"freeItemId": "<soapItemId>",
|
||||
"freeQty": 1
|
||||
}
|
||||
```
|
||||
`triggerItemId`/`triggerQty`/`freeItemId`/`freeQty` are optional on create — omit them for a plain
|
||||
SlabDiscount/FlatPercent scheme, or omit and set them later via `PUT .../free-goods-rule` if you want
|
||||
to create the shell first and configure the payout afterwards.
|
||||
|
||||
### POST `/api/schemes` (FreeBundle — created fully populated in one call)
|
||||
```json
|
||||
{
|
||||
"name": "Soap+Shampoo -> Free Toothbrush",
|
||||
"ruleType": "FreeBundle",
|
||||
"ruleConfig": null,
|
||||
"regionId": null,
|
||||
"eligibleSegment": null,
|
||||
"dateRangeFrom": "2026-08-01T00:00:00",
|
||||
"dateRangeTo": "2026-08-31T23:59:59",
|
||||
"agentLimitExempt": false,
|
||||
"baselineExpectedSales": null,
|
||||
"freeItemId": "<toothbrushId>",
|
||||
"freeQty": 1,
|
||||
"bundleComponents": [ { "itemId": "<soapId>", "qty": 1 }, { "itemId": "<shampooId>", "qty": 1 } ]
|
||||
}
|
||||
```
|
||||
`triggerItemId`/`triggerQty` are ignored for FreeBundle — the required items come from
|
||||
`bundleComponents` instead.
|
||||
|
||||
### PUT `/api/schemes/{id}/free-goods-rule`
|
||||
```json
|
||||
{ "triggerItemId": "<soapItemId>", "triggerQty": 10, "freeItemId": "<soapItemId>", "freeQty": 1 }
|
||||
```
|
||||
Same shape as the inline create fields — use this to add or change the free-goods payout on a
|
||||
scheme that was created without one.
|
||||
|
||||
### PUT `/api/schemes/{id}/bundle-components/{itemId}` (FreeBundle)
|
||||
```json
|
||||
{ "qty": 1 }
|
||||
```
|
||||
Use this to add/edit one bundle component after creation.
|
||||
|
||||
### POST `/api/schemes` (SlabDiscount)
|
||||
```json
|
||||
{
|
||||
"name": "Volume Discount",
|
||||
"ruleType": "SlabDiscount",
|
||||
"ruleConfig": "{\"tiers\":[{\"minOrderAmount\":5000,\"discountPercent\":5},{\"minOrderAmount\":10000,\"discountPercent\":8}]}",
|
||||
"regionId": null,
|
||||
"eligibleSegment": null,
|
||||
"dateRangeFrom": "2026-08-01T00:00:00",
|
||||
"dateRangeTo": "2026-08-31T23:59:59",
|
||||
"agentLimitExempt": false,
|
||||
"baselineExpectedSales": null
|
||||
}
|
||||
```
|
||||
|
||||
### POST `/api/orders/{id}/apply-scheme`
|
||||
```json
|
||||
{ "schemeId": "..." }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
- A scheme discount stacks with, but does not bypass, the per-role discount ceiling in
|
||||
[08_sales_agent_controls.md](./08_sales_agent_controls.md) unless explicitly flagged as an
|
||||
agent-limit-exempt scheme.
|
||||
- `getSchemeROI` requires a baseline (pre-scheme expected sales) to compare against — confirm data
|
||||
source before implementing (see Open Questions).
|
||||
1. A scheme discount stacks with, but does not bypass, the per-role discount ceiling in
|
||||
[08_sales_agent_controls.md](./08_sales_agent_controls.md) unless `AgentLimitExempt = true`.
|
||||
(Enforcement against the actual ceiling is deferred — 08_sales_agent_controls.md's discount
|
||||
ceiling isn't implemented in code yet; this is recorded as the target behavior.)
|
||||
2. `evaluateSchemeEligibility` matches a scheme to a store/order only if: the scheme's `RegionId` is
|
||||
null or matches the store's region; `EligibleSegment` is null or matches `Store.Segment`; and the
|
||||
order's date falls within `[DateRangeFrom, DateRangeTo]`.
|
||||
3. `BuyXGetY` eligibility: the order must contain at least `TriggerQty` of `TriggerItem`; the payout
|
||||
scales with how many multiples of `TriggerQty` were bought (`FreeQty × floor(boughtQty / TriggerQty)`).
|
||||
4. `FreeBundle` eligibility: the order must contain every `SchemeBundleComponent` in at least its
|
||||
listed `Qty`; payout is the flat `FreeQty` of `FreeItem` (no multiplier).
|
||||
5. `applySchemeDiscount` adds a zero-price `OrderItem` line for the free-goods payout (`UnitPrice = 0`,
|
||||
`Quantity = FreeQty`), rather than only recording a discount amount — the free line still needs to
|
||||
be picked, delivered, and stock-tracked like any other sold line.
|
||||
6. A free-goods redemption is blocked if the free item's available `StockBalance` (summed across all
|
||||
locations) is less than the payout `FreeQty` — same out-of-stock guard as a normal sold line.
|
||||
7. A scheme can only be redeemed once per order (`HasRedemptionAsync` check in `applySchemeDiscount`).
|
||||
8. `SchemeRedemption.FreeItemCostValue` snapshots `Item.CostPrice` at redemption time, so
|
||||
`trackSchemeSpend`/`getSchemeROI` stay accurate even after the item's cost price later changes.
|
||||
9. Free goods are typically still a taxable "deemed supply" at zero net value under GST/VAT-style
|
||||
regimes — not yet wired into a tax calculation, since no tax subsystem exists in this codebase
|
||||
yet. Flagged for whoever builds tax/invoicing.
|
||||
10. `trackSchemeSpend` = sum(`DiscountAmount`) + sum(`FreeItemCostValue × FreeQty`) across all
|
||||
redemptions. `getSchemeROI` = `(actualSales − BaselineExpectedSales) / totalSpend`, where
|
||||
`actualSales` is the sum of `Order.TotalAmount` for every distinct order that redeemed the scheme.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
- What counts as "incremental sales" for `getSchemeROI` — a manual baseline entered when the scheme
|
||||
is created, or a trailing-period average computed automatically?
|
||||
- What counts as "incremental sales" for `getSchemeROI` — **resolved for v1**: a manual
|
||||
`BaselineExpectedSales` entered at scheme creation, not a trailing-period average. Revisit if
|
||||
historical order data volume later makes an automatic trailing average preferable.
|
||||
- Per-role discount ceiling stacking (`AgentLimitExempt`) is unenforced pending
|
||||
[08_sales_agent_controls.md](./08_sales_agent_controls.md) having an actual ceiling implementation
|
||||
to stack against.
|
||||
- Deemed-supply tax treatment for free goods — deferred until a tax/invoicing subsystem exists.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
> Fill this section in during planning discussion before writing any code.
|
||||
### File structure created / touched
|
||||
```
|
||||
Features/
|
||||
Scheme/
|
||||
SchemeController.cs (also hosts SchemeOrderController for POST /api/orders/{id}/apply-scheme)
|
||||
SchemeDTOs.cs
|
||||
SchemeService.cs (EvaluateRule — the core eligibility/payout calculator; ApplySchemeAsync
|
||||
— the free-goods order-line + stock-check + redemption write path)
|
||||
ISchemeRepository.cs
|
||||
SchemeRepository.cs
|
||||
|
||||
Models/
|
||||
Scheme.cs (new — includes SchemeRuleType enum)
|
||||
SchemeBundleComponent.cs (new)
|
||||
SchemeRedemption.cs (new)
|
||||
Item.cs (extended — CostPrice)
|
||||
|
||||
Data/AppDBContext.cs
|
||||
add Schemes, SchemeRedemptions, SchemeBundleComponents DbSets; relationships (Scheme→TriggerItem/
|
||||
FreeItem restrict-delete, SchemeBundleComponent→Scheme cascade-delete, →Item restrict-delete,
|
||||
SchemeRedemption→Scheme/Order/FreeItem restrict-delete); unique index on
|
||||
SchemeBundleComponent(FK_SchemeId, FK_ItemId)
|
||||
|
||||
Migrations/
|
||||
AddPromotionsSchemes (applied)
|
||||
AddSchemeFreeGoodsRuleAndBundleComponents (applied)
|
||||
|
||||
Program.cs
|
||||
register ISchemeRepository/SchemeRepository, SchemeService
|
||||
```
|
||||
|
||||
### Eligibility + payout logic (pseudo)
|
||||
```
|
||||
EvaluateRule(scheme, orderItems):
|
||||
switch scheme.RuleType:
|
||||
BuyXGetY:
|
||||
boughtQty = sum(orderItems where ItemId = scheme.TriggerItemId).Quantity
|
||||
if boughtQty < scheme.TriggerQty: not eligible
|
||||
multiplier = boughtQty / scheme.TriggerQty // integer division
|
||||
→ eligible, FreeItemId = scheme.FreeItemId, FreeQty = scheme.FreeQty * multiplier
|
||||
|
||||
FreeBundle:
|
||||
missing = scheme.BundleComponents where sum(orderItems qty for that item) < component.Qty
|
||||
if missing.any(): not eligible
|
||||
→ eligible, FreeItemId = scheme.FreeItemId, FreeQty = scheme.FreeQty
|
||||
|
||||
FlatPercent / SlabDiscount:
|
||||
parse RuleConfig JSON, compute DiscountAmount off orderItems total
|
||||
```
|
||||
|
||||
### applySchemeDiscount flow (pseudo)
|
||||
```
|
||||
ApplySchemeAsync(orderId, schemeId):
|
||||
reject if scheme already redeemed against this order
|
||||
eligibility = EvaluateRule(scheme, order's items)
|
||||
reject if not eligible
|
||||
|
||||
if eligibility has a free-goods payout:
|
||||
check StockBalance across all locations >= FreeQty, else reject
|
||||
add OrderItem { ItemId = FreeItemId, Quantity = FreeQty, UnitPrice = 0 }
|
||||
redemption.FreeItemCostValue = freeItem.CostPrice ?? 0
|
||||
|
||||
save SchemeRedemption { DiscountAmount, FreeItemId, FreeQty, FreeItemCostValue }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Worked Example
|
||||
|
||||
Item `Soap-500ml` has `CostPrice = 12`. Store is in the "Gold" segment.
|
||||
|
||||
**Create the scheme (one call, fully populated):**
|
||||
```
|
||||
POST /api/schemes
|
||||
{ "name": "Soap Buy10Get1", "ruleType": "BuyXGetY", "ruleConfig": null,
|
||||
"regionId": null, "eligibleSegment": "Gold",
|
||||
"dateRangeFrom": "2026-08-01", "dateRangeTo": "2026-08-31",
|
||||
"agentLimitExempt": false, "baselineExpectedSales": 50000,
|
||||
"triggerItemId": "<soapId>", "triggerQty": 10, "freeItemId": "<soapId>", "freeQty": 1 }
|
||||
→ Scheme { Id, ... }
|
||||
```
|
||||
|
||||
**Store places an order** for 20 units of `Soap-500ml` → `Order { Id, TotalAmount }`.
|
||||
|
||||
**Check eligibility:**
|
||||
```
|
||||
GET /api/schemes/eligible?storeId=...&orderId=...
|
||||
→ [{ "schemeId": "...", "eligible": true, "freeItemId": "<soapId>", "freeQty": 2 }]
|
||||
```
|
||||
20 ÷ 10 = 2 multiples → 2 free units.
|
||||
|
||||
**Apply it:**
|
||||
```
|
||||
POST /api/orders/{orderId}/apply-scheme
|
||||
{ "schemeId": "..." }
|
||||
```
|
||||
Adds an `OrderItem` line (`Soap-500ml`, qty 2, `UnitPrice = 0`) and a `SchemeRedemption` with
|
||||
`FreeQty = 2`, `FreeItemCostValue = 12`.
|
||||
|
||||
**Spend/ROI:**
|
||||
```
|
||||
GET /api/schemes/{id}/spend
|
||||
→ { "totalDiscountSpend": 0, "totalFreeGoodsCostSpend": 24, "totalSpend": 24, "redemptionCount": 1 }
|
||||
|
||||
GET /api/schemes/{id}/roi
|
||||
→ { "baselineExpectedSales": 50000, "actualSales": 62000, "incrementalSales": 12000,
|
||||
"totalSpend": 24, "roi": 500.0 }
|
||||
```
|
||||
|
||||
**FreeBundle variant** ("buy Soap + Shampoo, get a free Toothbrush") — also one call:
|
||||
```
|
||||
POST /api/schemes
|
||||
{ "name": "Soap+Shampoo -> Free Toothbrush", "ruleType": "FreeBundle", "ruleConfig": null,
|
||||
"regionId": null, "eligibleSegment": null,
|
||||
"dateRangeFrom": "2026-08-01", "dateRangeTo": "2026-08-31",
|
||||
"agentLimitExempt": false, "baselineExpectedSales": null,
|
||||
"freeItemId": "<toothbrushId>", "freeQty": 1,
|
||||
"bundleComponents": [ { "itemId": "<soapId>", "qty": 1 }, { "itemId": "<shampooId>", "qty": 1 } ] }
|
||||
```
|
||||
Eligibility now requires both Soap ≥1 and Shampoo ≥1 in the order; payout is 1 free toothbrush,
|
||||
flat (no multiplier). Components/payout can still be edited afterwards via
|
||||
`PUT .../bundle-components/{itemId}` and `PUT .../free-goods-rule`.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user