Compare commits

..

90 Commits

Author SHA1 Message Date
c5c5088724 removed logs 2025-02-04 11:38:11 +04:00
d1d570b40f Fixed issue in loading space model 2025-02-04 11:36:26 +04:00
5e5f127a4b duplicate should be in same vertical offset 2025-02-04 00:12:20 +04:00
6f51c2d2b6 provide all tags on edit space 2025-02-03 22:23:53 +04:00
72241cba6c added error validation 2025-02-03 14:47:05 +04:00
64e3fb7f34 removed print 2025-02-02 23:38:04 +04:00
e6e46be9b4 fixed issues in create space and duplicate 2025-02-02 23:16:34 +04:00
91dfd53477 fixed issue in creating space 2025-02-02 21:02:58 +04:00
916b606cb1 deleting subspace won't remove tag 2025-01-30 23:26:26 +04:00
29c444eede updated tags 2025-01-30 22:01:08 +04:00
9dd6c9e1e7 updated logic of adding tag to subspace 2025-01-30 21:15:00 +04:00
bf5b39e742 add empty subspace validation 2025-01-30 15:00:40 +04:00
a294988558 add subspace and space information 2025-01-30 10:09:21 +04:00
09c1a785e5 add subspace validation 2025-01-29 22:03:56 +04:00
c173df934d added all tags 2025-01-29 12:24:12 +04:00
e4262d08a5 fixed ok button 2025-01-29 11:40:53 +04:00
4bae7bb9fb fixed update space 2025-01-29 11:14:12 +04:00
073916d4ac updated text theme 2025-01-29 10:21:06 +04:00
8870467fe4 fixed the edit flow of space 2025-01-29 09:56:10 +04:00
9331193e90 added tags and subspace to update space 2025-01-29 09:55:36 +04:00
45b0b67fe0 make counter widget work only for add device 2025-01-29 09:53:06 +04:00
9091af2661 fixed text style 2025-01-28 13:27:05 +04:00
4b7f4d4279 fixed calculating products on add another device 2025-01-28 11:39:34 +04:00
e61cfd7e49 added option to update subspace 2025-01-28 10:48:14 +04:00
788fb75a68 fixed UI alignment 2025-01-27 18:12:57 +04:00
c72297e0c8 updated the duplicate 2025-01-27 14:21:07 +04:00
d0c6b13072 updated edit flow 2025-01-27 01:25:04 +04:00
812dc4792b fixed duplicate 2025-01-27 01:19:08 +04:00
4907eebc42 added duplicate 2025-01-27 00:33:50 +04:00
9167c8da29 fixed space model updates 2025-01-25 01:29:21 +04:00
4258ccdfbd fix header issue 2025-01-24 20:43:45 +04:00
cb71b51565 community header 2025-01-24 20:41:31 +04:00
d4ed4efcd8 validation fix 2025-01-23 17:48:11 +04:00
dac045146e duplicate name validation 2025-01-23 17:02:32 +04:00
5563197e9d add validation 2025-01-23 15:20:36 +04:00
7268253e35 fixed button validation 2025-01-23 11:45:11 +04:00
24f7ab6af8 changed subspace label 2025-01-23 10:18:20 +04:00
65d00c923a updated tag issue for subspace 2025-01-23 00:02:28 +04:00
830725254f removed logs 2025-01-22 17:22:58 +04:00
ba7db3a5fb updated subspace edit flow 2025-01-22 17:21:35 +04:00
f35b699d4c fixed the edit flow for space model 2025-01-22 12:49:47 +04:00
7ffdc67016 added product comparison 2025-01-22 12:48:46 +04:00
18afc4f563 fixed issues 2025-01-21 20:37:21 +04:00
44d95f5701 fixed index 2025-01-21 20:29:15 +04:00
e47f3d6d59 fixed space model creation 2025-01-21 20:26:30 +04:00
788ea27de1 Merge branch 'feat/space-creation-update' into bugfix/space-edit 2025-01-21 18:40:33 +04:00
81e9e58627 fixed duplicate tag issue 2025-01-21 15:21:25 +04:00
25eae3dfaa Merge pull request #66 from SyncrowIOT/feat/space-creation-update
Feat/space creation update
2025-01-21 11:42:43 +04:00
0e912207e5 flow 2025-01-21 11:41:53 +04:00
eb53671e3a edit flow 2025-01-20 21:47:22 +04:00
2f6bd31aa2 helper class 2025-01-20 10:52:23 +04:00
fe680d15f2 edit and create 2025-01-20 10:28:46 +04:00
440263e2f9 added initial flow 2025-01-18 00:32:48 +04:00
ec5b7d4395 changed button name 2025-01-17 23:53:43 +04:00
7109421358 fixed first time flow 2025-01-17 23:51:56 +04:00
145086b9de updated grid view 2025-01-17 12:40:17 +04:00
bae5ae17a7 updated the condition 2025-01-16 10:17:57 +04:00
9706c2655c added color 2025-01-16 02:15:24 +04:00
8a95f93556 fixed list view 2025-01-16 02:14:04 +04:00
60028cdf78 only appears the separator if there is both space model and product 2025-01-16 02:03:08 +04:00
c12c73f20a add close button color 2025-01-16 00:10:45 +04:00
a7256c8d5d updated duplication ui 2025-01-15 11:29:19 +04:00
5975adb5e2 cleaned subspace model create 2025-01-15 10:22:42 +04:00
0bb24604bc fixed subspace create 2025-01-15 09:39:26 +04:00
cf2690123e revert back 2025-01-14 12:22:59 +04:00
a220483310 revert back 2025-01-14 12:22:51 +04:00
12df07e681 changed chip to list 2025-01-14 12:14:48 +04:00
59eafc99a5 Merge pull request #67 from SyncrowIOT/roles_permissions_issues
fixes filter and table view and add user dialog
2025-01-13 15:41:33 +03:00
db7eaa53af check type isNotEmpty 2025-01-13 15:40:38 +03:00
20a9f19480 check if title is not empty and remove nullable 2025-01-13 14:36:17 +03:00
a4e7f30411 moved pagination to bloc 2025-01-13 14:14:09 +04:00
210fbf7497 initialize with const 2025-01-13 12:16:49 +04:00
acbb6ca7c0 removed try catch 2025-01-13 12:12:22 +04:00
eb7eeebf18 fixes add user view and table and user status 2025-01-13 11:07:18 +03:00
15023e5882 fixes filter and table view and add user dialog 2025-01-12 15:32:03 +03:00
408c40aa60 revert 2025-01-12 12:12:14 +04:00
2abe7a6feb revert 2025-01-12 12:11:32 +04:00
a381fd317d added space delete 2025-01-12 12:10:54 +04:00
a588351482 fixed space creation api 2025-01-12 11:37:10 +04:00
1be52adcc8 added assign tag 2025-01-12 10:43:47 +04:00
3c5e0a7778 device type select 2025-01-12 10:04:44 +04:00
6591ef1664 load space models 2025-01-12 09:25:29 +04:00
cfc1b544b7 added subspaces 2025-01-12 09:10:33 +04:00
15640ff0df added space model select 2025-01-12 01:15:44 +04:00
bfbc32d51b moved select space a bit down 2025-01-11 18:37:34 +04:00
8aa493a15e added space model link to space dialog 2025-01-11 15:42:35 +04:00
e70df16de3 added asset 2025-01-09 16:39:54 +04:00
a7e7554813 added buttons 2025-01-09 16:39:46 +04:00
1ab8c8341d updated widget 2025-01-09 16:31:20 +04:00
67516817ec add asset validation 2025-01-09 16:18:19 +04:00
108 changed files with 7047 additions and 2160 deletions

View File

@ -0,0 +1,16 @@
<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M17.9807 2.67199L16.6413 0.219727H7.91051C7.43122 0.219727 7.04266 0.608281 7.04266 1.08758V16.605C7.04266 17.0843 7.43122 17.4729 7.91051 17.4729H18.2257C18.705 17.4729 19.0935 17.0843 19.0935 16.605V16.5459H19.7312V3.8127L17.9807 2.67199Z" fill="#60B7FF"/>
<path d="M18.1513 6.23445H9.12553C8.95881 6.23445 8.82373 6.09934 8.82373 5.93266C8.82373 5.76598 8.95885 5.63086 9.12553 5.63086H18.1513C18.318 5.63086 18.4531 5.76598 18.4531 5.93266C18.4531 6.09934 18.318 6.23445 18.1513 6.23445Z" fill="#0055A3"/>
<path d="M18.1513 8.54891H9.12553C8.95881 8.54891 8.82373 8.41379 8.82373 8.24711C8.82373 8.08043 8.95885 7.94531 9.12553 7.94531H18.1513C18.318 7.94531 18.4531 8.08043 18.4531 8.24711C18.4531 8.41379 18.318 8.54891 18.1513 8.54891Z" fill="#0055A3"/>
<path d="M18.1513 10.8634H9.12553C8.95881 10.8634 8.82373 10.7282 8.82373 10.5616C8.82373 10.3949 8.95885 10.2598 9.12553 10.2598H18.1513C18.318 10.2598 18.4531 10.3949 18.4531 10.5616C18.4531 10.7282 18.318 10.8634 18.1513 10.8634Z" fill="#0055A3"/>
<path d="M18.1513 13.1778H9.12556C8.95884 13.1778 8.82376 13.0427 8.82376 12.876C8.82376 12.7093 8.95888 12.5742 9.12556 12.5742H18.1513C18.3181 12.5742 18.4531 12.7093 18.4531 12.876C18.4531 13.0427 18.3181 13.1778 18.1513 13.1778Z" fill="#0055A3"/>
<path d="M19.0935 3.39648V16.6044C19.0935 17.0837 18.7049 17.4722 18.2256 17.4722H19.3663C19.8456 17.4722 20.2342 17.0837 20.2342 16.6044V3.81203L19.0935 3.39648Z" fill="#26A6FE"/>
<path d="M17.5091 3.8127H20.2342L16.6413 0.219727V2.94484C16.6413 3.42414 17.0298 3.8127 17.5091 3.8127Z" fill="#004281"/>
<path d="M11.4172 19.7805C11.8965 19.7805 12.2851 19.392 12.2851 18.9127V18.8937H12.8297V6.12031L11.039 4.78906L9.83279 2.52734H1.10204C0.622747 2.52734 0.234192 2.9159 0.234192 3.3952V18.9127C0.234192 19.392 0.622747 19.7805 1.10204 19.7805H11.4172Z" fill="#D5EDFF"/>
<path d="M12.285 4.97852V6.11922V18.9116C12.285 19.3909 11.8964 19.7794 11.4171 19.7794H12.5578C13.0371 19.7794 13.4257 19.3909 13.4257 18.9116V6.11922L12.285 4.97852Z" fill="#D8ECFE"/>
<path d="M10.7006 6.12031H13.4258L9.83279 2.52734V5.25246C9.83276 5.73176 10.2213 6.12031 10.7006 6.12031Z" fill="#B3DAFE"/>
<path d="M11.3429 8.54891H2.31709C2.15037 8.54891 2.01529 8.41379 2.01529 8.24711C2.01529 8.08043 2.15041 7.94531 2.31709 7.94531H11.3429C11.5096 7.94531 11.6447 8.08043 11.6447 8.24711C11.6447 8.41379 11.5096 8.54891 11.3429 8.54891Z" fill="#82AEE3"/>
<path d="M11.3428 10.8634H2.31706C2.15034 10.8634 2.01526 10.7282 2.01526 10.5616C2.01526 10.3949 2.15038 10.2598 2.31706 10.2598H11.3428C11.5096 10.2598 11.6446 10.3949 11.6446 10.5616C11.6446 10.7282 11.5096 10.8634 11.3428 10.8634Z" fill="#82AEE3"/>
<path d="M11.3428 13.1778H2.31706C2.15034 13.1778 2.01526 13.0427 2.01526 12.876C2.01526 12.7093 2.15038 12.5742 2.31706 12.5742H11.3428C11.5096 12.5742 11.6446 12.7093 11.6446 12.876C11.6446 13.0427 11.5096 13.1778 11.3428 13.1778Z" fill="#82AEE3"/>
<path d="M11.3428 15.4923H2.31706C2.15034 15.4923 2.01526 15.3571 2.01526 15.1905C2.01526 15.0238 2.15038 14.8887 2.31706 14.8887H11.3428C11.5096 14.8887 11.6446 15.0238 11.6446 15.1905C11.6447 15.3571 11.5096 15.4923 11.3428 15.4923Z" fill="#82AEE3"/>
</svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@ -0,0 +1,22 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g filter="url(#filter0_d_4618_3290)">
<path d="M18.7967 7.35156V19.8515C18.7967 21.0362 17.8329 22 16.6482 22H4.14825C2.9636 22 1.99982 21.0362 1.99982 19.8515V7.35156C1.99982 6.16691 2.9636 5.20312 4.14825 5.20312H16.6482C17.8329 5.20312 18.7967 6.16691 18.7967 7.35156Z" fill="#EDF2F2"/>
<path d="M18.7967 19.8515C18.7967 21.0361 17.8329 21.9999 16.6482 21.9999H4.14825C3.55591 21.9999 3.0188 21.7589 2.62978 21.3699L18.1667 5.83301C18.5557 6.22203 18.7967 6.75914 18.7967 7.35148V19.8515Z" fill="#C9DCDC"/>
<path d="M9.28417 14.7153C9.12722 14.5583 9.07241 14.3262 9.14265 14.1157L9.97128 11.6297C10 11.5434 10.0485 11.465 10.1128 11.4007L17.8468 3.66674C18.0756 3.43791 18.4466 3.43791 18.6754 3.66674L20.3327 5.324C20.5615 5.55283 20.5615 5.9238 20.3327 6.15263L12.5987 13.8866C12.5344 13.9509 12.456 13.9994 12.3697 14.0281L9.88374 14.8567C9.67323 14.927 9.44109 14.8722 9.28417 14.7153Z" fill="#4998EE"/>
<path d="M19.504 4.49512L9.28413 14.715C9.44105 14.8719 9.6732 14.9267 9.88374 14.8565L12.3697 14.0279C12.456 13.9992 12.5344 13.9507 12.5987 13.8864L20.3327 6.15242C20.5615 5.92359 20.5615 5.55261 20.3327 5.32379L19.504 4.49512Z" fill="#176EDE"/>
<path d="M20.3327 6.15305L17.8467 3.66711L19.2278 2.28602C19.6092 1.90466 20.2275 1.90466 20.6089 2.28602L21.7137 3.39087C22.0951 3.77223 22.0951 4.39055 21.7137 4.77192L20.3327 6.15305Z" fill="#FFE137"/>
<path d="M21.1613 2.83789L19.0897 4.90949L20.3327 6.15245L21.7138 4.77136C22.0951 4.39 22.0951 3.77168 21.7138 3.39031L21.1613 2.83789Z" fill="#FAC814"/>
</g>
<defs>
<filter id="filter0_d_4618_3290" x="-0.000183105" y="0" width="24" height="24" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset/>
<feGaussianBlur stdDeviation="1"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_4618_3290"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_4618_3290" result="shape"/>
</filter>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

12
assets/icons/link.svg Normal file
View File

@ -0,0 +1,12 @@
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
<g id="Group 440">
<path id="Vector" d="M6.7986 0.892983L4.84001 2.85148C4.48185 3.20973 4.23182 3.63572 4.08964 4.08854C3.62464 4.23503 3.19865 4.49284 2.85148 4.84001L0.892983 6.7986C-0.29757 7.98915 -0.297753 9.91625 0.892983 11.107C2.08354 12.2976 4.01072 12.2977 5.20146 11.107L7.15996 9.14848C7.5182 8.79033 7.76814 8.36433 7.91032 7.91142C8.37541 7.76503 8.80132 7.50713 9.14848 7.15996L11.107 5.20146C12.2976 4.01081 12.2978 2.08372 11.107 0.892983C9.91643 -0.29757 7.98933 -0.297753 6.7986 0.892983ZM4.17735 6.1656C4.32576 6.5276 4.54658 6.86653 4.84001 7.15996C5.1251 7.44496 5.46431 7.67027 5.83418 7.82289L3.87577 9.78139C3.41893 10.2381 2.67552 10.2382 2.21867 9.78139C1.76182 9.32445 1.76182 8.58113 2.21867 8.12428L4.17717 6.16569C4.17726 6.16569 4.17726 6.16569 4.17735 6.1656ZM6.82854 8.81706L4.86995 10.7756C3.86259 11.783 2.23194 11.7831 1.2244 10.7756C0.216957 9.76821 0.216866 8.13747 1.2244 7.13002L3.1829 5.17143C3.41105 4.94328 3.67939 4.76082 3.9719 4.63255C3.92823 4.9897 3.94819 5.34263 4.02427 5.67991C3.96128 5.72697 3.90159 5.77843 3.84574 5.83427L1.88725 7.79277C1.24766 8.43245 1.24766 9.47313 1.88725 10.1127C2.52683 10.7523 3.56752 10.7523 4.2072 10.1127L6.16569 8.15422C6.80592 7.5139 6.80601 6.47459 6.16569 5.83427C5.82365 5.49223 5.74034 4.99492 5.90358 4.57753C6.24891 4.70598 6.56587 4.90876 6.82854 5.17143C7.8336 6.1765 7.83369 7.8119 6.82854 8.81706ZM10.7756 4.86995L8.81706 6.82854C8.58891 7.05669 8.32057 7.23915 8.02806 7.36742C8.07173 7.01027 8.05177 6.65733 7.97578 6.32005C8.03868 6.27299 8.09846 6.22154 8.15422 6.16569L10.1128 4.2072C10.7524 3.56761 10.7524 2.52683 10.1128 1.88725C9.5385 1.31303 8.64028 1.25379 7.99913 1.71229C7.89384 1.78755 7.86958 1.93394 7.94484 2.03922C8.0201 2.14451 8.16649 2.16886 8.27177 2.09352C8.73952 1.75907 9.37434 1.81162 9.78139 2.21867C10.2382 2.67552 10.2382 3.41883 9.78139 3.87577L7.8228 5.83427C7.8228 5.83427 7.8228 5.83427 7.82271 5.83436C7.67421 5.47236 7.45338 5.13344 7.15996 4.84001C6.87495 4.555 6.53566 4.32969 6.16578 4.17707L6.96431 3.37855C7.05577 3.28709 7.05577 3.13868 6.96431 3.04713C6.87276 2.95567 6.72444 2.95567 6.63289 3.04713L5.83427 3.84574C5.19404 4.48597 5.19395 5.52528 5.83427 6.16569C6.17631 6.50764 6.25963 7.00505 6.09639 7.42244C5.75105 7.29399 5.43409 7.0912 5.17143 6.82844C4.16645 5.82347 4.16636 4.18797 5.17143 3.1829L7.13002 1.2244C8.13737 0.216957 9.76811 0.216774 10.7756 1.2244C11.783 2.23176 11.7831 3.8625 10.7756 4.86995Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_2" d="M7.69571 2.55103C7.69571 2.68048 7.59079 2.7854 7.46143 2.7854C7.33197 2.7854 7.22705 2.68048 7.22705 2.55103C7.22705 2.42157 7.33197 2.31665 7.46143 2.31665C7.59079 2.31665 7.69571 2.42157 7.69571 2.55103Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_3" d="M3.18286 3.1831C3.27441 3.09164 3.27441 2.94323 3.18286 2.85168L2.18859 1.85741C2.09704 1.76595 1.94872 1.76595 1.85717 1.85741C1.76571 1.94897 1.76571 2.09737 1.85717 2.18893L2.85143 3.18319C2.94308 3.27465 3.09139 3.27465 3.18286 3.1831Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_4" d="M0.891022 3.9375C0.761658 3.9375 0.656738 4.04242 0.656738 4.17178C0.656738 4.30124 0.761658 4.40616 0.891022 4.40616H2.29718C2.42655 4.40616 2.53147 4.30124 2.53147 4.17178C2.53147 4.04242 2.42655 3.9375 2.29718 3.9375H0.891022Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_5" d="M3.93774 0.821289V2.22736C3.93774 2.35672 4.04266 2.46173 4.17203 2.46173C4.30148 2.46173 4.4064 2.35672 4.4064 2.22736V0.821289C4.4064 0.691834 4.30148 0.586914 4.17203 0.586914C4.04266 0.586914 3.93774 0.691834 3.93774 0.821289Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_6" d="M8.8172 8.81738C8.72565 8.90884 8.72565 9.05724 8.8172 9.1488L9.81146 10.1431C9.85724 10.1888 9.91721 10.2117 9.97717 10.2117C10.184 10.2117 10.291 9.95986 10.1429 9.81164L9.14862 8.81738C9.05707 8.72591 8.90875 8.72591 8.8172 8.81738Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_7" d="M8.03882 11.1785V9.77237C8.03882 9.64301 7.93381 9.53809 7.80444 9.53809C7.67499 9.53809 7.57007 9.64301 7.57007 9.77237V11.1785C7.57007 11.3079 7.67499 11.4128 7.80444 11.4128C7.93381 11.4128 8.03882 11.3079 8.03882 11.1785Z" fill="#023DFE" fill-opacity="0.7"/>
<path id="Vector_8" d="M11.1793 8.03906C11.3086 8.03906 11.4135 7.93405 11.4135 7.80469C11.4135 7.67523 11.3086 7.57031 11.1793 7.57031H9.7731C9.64374 7.57031 9.53882 7.67523 9.53882 7.80469C9.53882 7.93405 9.64374 8.03906 9.7731 8.03906H11.1793Z" fill="#023DFE" fill-opacity="0.7"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.5 KiB

View File

@ -0,0 +1,9 @@
<svg width="16" height="20" viewBox="0 0 16 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11.8069 19.9998H3.50035C2.16411 19.9998 1.08087 18.9165 1.08087 17.5804V4.51562H14.2262V17.5804C14.2262 18.9165 13.1432 19.9998 11.8069 19.9998Z" fill="#D8D8D8"/>
<path d="M1.08087 4.51562V5.48335H12.3715C12.8168 5.48335 13.1779 5.84438 13.1779 6.2898V17.3384C13.1779 18.2292 12.4557 18.9513 11.5649 18.9513H2.4519C2.05409 18.9513 1.67887 18.8547 1.34775 18.6844C1.74907 19.4652 2.56207 19.9998 3.50035 19.9998H11.8069C13.1432 19.9998 14.2262 18.9165 14.2262 17.5803V4.51562H1.08087Z" fill="#BABABA"/>
<path d="M14.2667 1.77417H10.7439L10.1633 0.612956C9.9742 0.234837 9.5941 0 9.17142 0H6.13594C5.71311 0 5.33316 0.234837 5.1441 0.612956L4.56349 1.77417H1.04063C0.595221 1.77417 0.234192 2.1352 0.234192 2.58061V3.70978C0.234192 4.15504 0.595221 4.51622 1.04063 4.51622H14.2667C14.7121 4.51622 15.0732 4.15504 15.0732 3.70978V2.58077C15.0732 2.1352 14.7121 1.77417 14.2667 1.77417ZM5.68503 0.8835C5.77094 0.71153 5.94368 0.604869 6.13594 0.604869H9.17142C9.36354 0.604869 9.53627 0.71153 9.62218 0.8835L10.0676 1.77417H5.23977L5.68503 0.8835Z" fill="#757575"/>
<path d="M14.2668 1.77441H12.9763C13.4217 1.77441 13.7829 2.13544 13.7829 2.58086V3.71003C13.7829 4.15529 13.4217 4.51647 12.9763 4.51647H14.2668C14.7122 4.51647 15.0732 4.15529 15.0732 3.71003V2.58101C15.0732 2.13544 14.7122 1.77441 14.2668 1.77441Z" fill="#595959"/>
<path d="M11.3634 17.5C10.918 17.5 10.5569 17.139 10.5569 16.6935V9.15312C10.5569 8.70771 10.918 8.34668 11.3634 8.34668C11.8088 8.34668 12.1698 8.70771 12.1698 9.15312V16.6935C12.1698 17.139 11.8088 17.5 11.3634 17.5Z" fill="#757575"/>
<path d="M3.94398 17.5C4.38924 17.5 4.75043 17.139 4.75043 16.6935V9.15312C4.75043 8.70771 4.38924 8.34668 3.94398 8.34668C3.49857 8.34668 3.13739 8.70771 3.13739 9.15312V16.6935C3.13739 17.139 3.49857 17.5 3.94398 17.5Z" fill="#757575"/>
<path d="M7.65361 17.5C7.2082 17.5 6.84717 17.139 6.84717 16.6935V9.15312C6.84717 8.70771 7.2082 8.34668 7.65361 8.34668C8.09902 8.34668 8.46005 8.70771 8.46005 9.15312V16.6935C8.46005 17.139 8.09902 17.5 7.65361 17.5Z" fill="#757575"/>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@ -0,0 +1,138 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class DialogDropdown extends StatefulWidget {
final List<String> items;
final ValueChanged<String> onSelected;
final String? selectedValue;
const DialogDropdown({
Key? key,
required this.items,
required this.onSelected,
this.selectedValue,
}) : super(key: key);
@override
_DialogDropdownState createState() => _DialogDropdownState();
}
class _DialogDropdownState extends State<DialogDropdown> {
bool _isOpen = false;
late OverlayEntry _overlayEntry;
@override
void initState() {
super.initState();
}
void _toggleDropdown() {
if (_isOpen) {
_closeDropdown();
} else {
_openDropdown();
}
}
void _openDropdown() {
_overlayEntry = _createOverlayEntry();
Overlay.of(context).insert(_overlayEntry);
_isOpen = true;
}
void _closeDropdown() {
_overlayEntry.remove();
_isOpen = false;
}
OverlayEntry _createOverlayEntry() {
final renderBox = context.findRenderObject() as RenderBox;
final size = renderBox.size;
final offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(
builder: (context) {
return GestureDetector(
onTap: () {
_closeDropdown();
},
behavior: HitTestBehavior.translucent,
child: Stack(
children: [
Positioned(
left: offset.dx,
top: offset.dy + size.height,
width: size.width,
child: Material(
elevation: 4.0,
child: Container(
color: ColorsManager.whiteColors,
constraints: const BoxConstraints(
maxHeight: 200.0, // Set max height for dropdown
),
child: ListView.builder(
shrinkWrap: true,
itemCount: widget.items.length,
itemBuilder: (context, index) {
final item = widget.items[index];
return Container(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(
color: ColorsManager.lightGrayBorderColor,
width: 1.0,
),
),
),
child: ListTile(
title: Text(
item,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: ColorsManager.textPrimaryColor,
),
),
onTap: () {
widget.onSelected(item);
_closeDropdown();
},
),
);
},
),
),
),
),
],
),
);
},
);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _toggleDropdown,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
decoration: BoxDecoration(
border: Border.all(color: ColorsManager.transparentColor),
borderRadius: BorderRadius.circular(8.0),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
widget.selectedValue ?? 'Select an item',
style: Theme.of(context).textTheme.bodyMedium,
),
const Icon(Icons.arrow_drop_down),
],
),
),
);
}
}

View File

@ -0,0 +1,160 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class DialogTextfieldDropdown extends StatefulWidget {
final List<String> items;
final ValueChanged<String> onSelected;
final String? initialValue;
const DialogTextfieldDropdown({
Key? key,
required this.items,
required this.onSelected,
this.initialValue,
}) : super(key: key);
@override
_DialogTextfieldDropdownState createState() =>
_DialogTextfieldDropdownState();
}
class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
bool _isOpen = false;
late OverlayEntry _overlayEntry;
final TextEditingController _controller = TextEditingController();
late List<String> _filteredItems; // Filtered items list
@override
void initState() {
super.initState();
_controller.text = widget.initialValue ?? 'Select Tag';
_filteredItems = List.from(widget.items); // Initialize filtered items
}
void _toggleDropdown() {
if (_isOpen) {
_closeDropdown();
} else {
_openDropdown();
}
}
void _openDropdown() {
_overlayEntry = _createOverlayEntry();
Overlay.of(context).insert(_overlayEntry);
_isOpen = true;
}
void _closeDropdown() {
_overlayEntry.remove();
_isOpen = false;
}
OverlayEntry _createOverlayEntry() {
final renderBox = context.findRenderObject() as RenderBox;
final size = renderBox.size;
final offset = renderBox.localToGlobal(Offset.zero);
return OverlayEntry(
builder: (context) {
return GestureDetector(
onTap: () {
_closeDropdown();
},
behavior: HitTestBehavior.translucent,
child: Stack(
children: [
Positioned(
left: offset.dx,
top: offset.dy + size.height,
width: size.width,
child: Material(
elevation: 4.0,
child: Container(
color: ColorsManager.whiteColors,
constraints: const BoxConstraints(
maxHeight: 200.0,
),
child: ListView.builder(
shrinkWrap: true,
itemCount: _filteredItems.length,
itemBuilder: (context, index) {
final item = _filteredItems[index];
return Container(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(
color: ColorsManager.lightGrayBorderColor,
width: 1.0,
),
),
),
child: ListTile(
title: Text(item,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: ColorsManager.textPrimaryColor)),
onTap: () {
_controller.text = item;
widget.onSelected(item);
setState(() {
_filteredItems
.remove(item); // Remove selected item
});
_closeDropdown();
},
),
);
},
),
),
),
),
],
),
);
},
);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _toggleDropdown,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
decoration: BoxDecoration(
border: Border.all(color: ColorsManager.transparentColor),
borderRadius: BorderRadius.circular(8.0),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: TextFormField(
controller: _controller,
onChanged: (value) {
setState(() {
_filteredItems = widget.items
.where((item) =>
item.toLowerCase().contains(value.toLowerCase()))
.toList(); // Filter items dynamically
});
widget.onSelected(value);
},
style: Theme.of(context).textTheme.bodyMedium,
decoration: const InputDecoration(
hintText: 'Enter or Select tag',
border: InputBorder.none,
),
),
),
const Icon(Icons.arrow_drop_down),
],
),
),
);
}
}

39
lib/common/edit_chip.dart Normal file
View File

@ -0,0 +1,39 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class EditChip extends StatelessWidget {
final String label;
final VoidCallback onTap;
final Color labelColor;
final Color backgroundColor;
final Color borderColor;
final double borderRadius;
const EditChip({
Key? key,
this.label = 'Edit',
required this.onTap,
this.labelColor = ColorsManager.spaceColor,
this.backgroundColor = ColorsManager.whiteColors,
this.borderColor = ColorsManager.spaceColor,
this.borderRadius = 16.0,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Chip(
label: Text(
label,
style: Theme.of(context).textTheme.bodySmall!.copyWith(color: labelColor)
),
backgroundColor: backgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRadius),
side: BorderSide(color: borderColor),
),
),
);
}
}

View File

@ -19,12 +19,14 @@ class DefaultButton extends StatelessWidget {
this.padding,
this.borderColor,
this.elevation,
this.borderWidth = 1.0,
});
final void Function()? onPressed;
final Widget child;
final double? height;
final bool isSecondary;
final double? borderRadius;
final double borderWidth;
final bool enabled;
final double? padding;
final bool isDone;
@ -66,13 +68,16 @@ class DefaultButton extends StatelessWidget {
}),
shape: WidgetStateProperty.all(
RoundedRectangleBorder(
side: BorderSide(color: borderColor ?? Colors.transparent),
side: BorderSide(
color: borderColor ?? Colors.transparent,
width: borderWidth,
),
borderRadius: BorderRadius.circular(borderRadius ?? 20),
),
),
fixedSize: height != null
? WidgetStateProperty.all(Size.fromHeight(height!))
: null,
? WidgetStateProperty.all(Size.fromHeight(height!))
: null,
padding: WidgetStateProperty.all(
EdgeInsets.all(padding ?? 10),
),

View File

@ -0,0 +1,47 @@
class DeviceSubspace {
final String uuid;
final DateTime? createdAt;
final DateTime? updatedAt;
final String subspaceName;
final bool disabled;
DeviceSubspace({
required this.uuid,
this.createdAt,
this.updatedAt,
required this.subspaceName,
required this.disabled,
});
factory DeviceSubspace.fromJson(Map<String, dynamic> json) {
return DeviceSubspace(
uuid: json['uuid'] as String,
createdAt: json['createdAt'] != null
? DateTime.tryParse(json['createdAt'].toString())
: null,
updatedAt: json['updatedAt'] != null
? DateTime.tryParse(json['updatedAt'].toString())
: null,
subspaceName: json['subspaceName'] as String,
disabled: json['disabled'] as bool,
);
}
Map<String, dynamic> toJson() {
return {
'uuid': uuid,
'createdAt': createdAt?.toIso8601String(),
'updatedAt': updatedAt?.toIso8601String(),
'subspaceName': subspaceName,
'disabled': disabled,
};
}
static List<DeviceSubspace> listFromJson(List<dynamic> jsonList) {
return jsonList.map((json) => DeviceSubspace.fromJson(json)).toList();
}
static List<Map<String, dynamic>> listToJson(List<DeviceSubspace> subspaces) {
return subspaces.map((subspace) => subspace.toJson()).toList();
}
}

View File

@ -1,5 +1,6 @@
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_community.model.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_space_model.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_subspace.model.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/room.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/unit.dart';
import 'package:syncrow_web/pages/routiens/models/ac/ac_function.dart';
@ -47,6 +48,7 @@ class AllDevicesModel {
*/
DevicesModelRoom? room;
DeviceSubspace? subspace;
DevicesModelUnit? unit;
DeviceCommunityModel? community;
String? productUuid;
@ -77,6 +79,7 @@ class AllDevicesModel {
AllDevicesModel({
this.room,
this.subspace,
this.unit,
this.community,
this.productUuid,
@ -110,6 +113,9 @@ class AllDevicesModel {
room = (json['room'] != null && (json['room'] is Map))
? DevicesModelRoom.fromJson(json['room'])
: null;
subspace = (json['subspace'] != null && (json['subspace'] is Map))
? DeviceSubspace.fromJson(json['subspace'])
: null;
unit = (json['unit'] != null && (json['unit'] is Map))
? DevicesModelUnit.fromJson(json['unit'])
: null;
@ -288,6 +294,9 @@ SOS
if (room != null) {
data['room'] = room!.toJson();
}
if (subspace != null) {
data['subspace'] = subspace!.toJson();
}
if (unit != null) {
data['unit'] = unit!.toJson();
}
@ -330,6 +339,7 @@ SOS
return other is AllDevicesModel &&
other.room == room &&
other.subspace == subspace &&
other.unit == unit &&
other.productUuid == productUuid &&
other.productType == productType &&
@ -360,6 +370,7 @@ SOS
@override
int get hashCode {
return room.hashCode ^
subspace.hashCode ^
unit.hashCode ^
productUuid.hashCode ^
productType.hashCode ^

View File

@ -95,8 +95,9 @@ class DeviceControlDialog extends StatelessWidget with RouteControlsBasedCode {
]),
TableRow(
children: [
_buildInfoRow('Space Name:', device.unit?.name ?? 'N/A'),
_buildInfoRow('Room:', device.room?.name ?? 'N/A'),
_buildInfoRow('Space Name:',
device.spaces?.firstOrNull?.spaceName ?? 'N/A'),
_buildInfoRow('Room:', device.subspace?.subspaceName ?? 'N/A'),
],
),
TableRow(
@ -111,9 +112,13 @@ class DeviceControlDialog extends StatelessWidget with RouteControlsBasedCode {
),
_buildInfoRow(
'Battery Level:',
device.batteryLevel != null ? '${device.batteryLevel ?? 0}%' : "-",
device.batteryLevel != null
? '${device.batteryLevel ?? 0}%'
: "-",
statusColor: device.batteryLevel != null
? (device.batteryLevel! < 20 ? ColorsManager.red : ColorsManager.green)
? (device.batteryLevel! < 20
? ColorsManager.red
: ColorsManager.green)
: null,
),
],

View File

@ -42,7 +42,7 @@ class RolesUserModel {
invitedBy:
json['invitedBy'].toString().toLowerCase().replaceAll("_", " "),
phoneNumber: json['phoneNumber'],
jobTitle: json['jobTitle'].toString(),
jobTitle: json['jobTitle'] ?? "-",
createdDate: json['createdDate'],
createdTime: json['createdTime'],
);

View File

@ -114,7 +114,7 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
currentStep++;
if (currentStep == 2) {
_blocRole.add(
CheckStepStatus(isEditUser: false));
const CheckStepStatus(isEditUser: false));
} else if (currentStep == 3) {
_blocRole
.add(const CheckSpacesStepStatus());
@ -151,11 +151,11 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
Widget _getFormContent() {
switch (currentStep) {
case 1:
return BasicsView(
return const BasicsView(
userId: '',
);
case 2:
return SpacesAccessView();
return const SpacesAccessView();
case 3:
return const RolesAndPermission();
default:
@ -172,7 +172,7 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
bloc.add(const CheckSpacesStepStatus());
currentStep = step;
Future.delayed(const Duration(milliseconds: 500), () {
bloc.add(ValidateBasicsStep());
bloc.add(const ValidateBasicsStep());
});
});
@ -237,10 +237,11 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
onTap: () {
setState(() {
currentStep = step;
bloc.add(CheckStepStatus(isEditUser: false));
bloc.add(const CheckStepStatus(isEditUser: false));
if (step3 == 3) {
bloc.add(const CheckRoleStepStatus());
}
});
},
child: Column(

View File

@ -4,7 +4,6 @@ import 'package:intl_phone_field/countries.dart';
import 'package:intl_phone_field/country_picker_dialog.dart';
import 'package:intl_phone_field/intl_phone_field.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -47,7 +46,9 @@ class BasicsView extends StatelessWidget {
),
Row(
children: [
Expanded(
SizedBox(
width: MediaQuery.of(context).size.width * 0.18,
height: MediaQuery.of(context).size.width * 0.08,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@ -76,12 +77,12 @@ class BasicsView extends StatelessWidget {
child: TextFormField(
style:
const TextStyle(color: ColorsManager.blackColor),
onChanged: (value) {
Future.delayed(const Duration(milliseconds: 200),
() {
_blocRole.add(ValidateBasicsStep());
});
},
// onChanged: (value) {
// Future.delayed(const Duration(milliseconds: 200),
// () {
// _blocRole.add(const ValidateBasicsStep());
// });
// },
controller: _blocRole.firstNameController,
decoration: inputTextFormDeco(
hintText: "Enter first name",
@ -103,7 +104,9 @@ class BasicsView extends StatelessWidget {
),
),
const SizedBox(width: 10),
Expanded(
SizedBox(
width: MediaQuery.of(context).size.width * 0.18,
height: MediaQuery.of(context).size.width * 0.08,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@ -128,12 +131,12 @@ class BasicsView extends StatelessWidget {
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
onChanged: (value) {
Future.delayed(const Duration(milliseconds: 200),
() {
_blocRole.add(ValidateBasicsStep());
});
},
// onChanged: (value) {
// Future.delayed(const Duration(milliseconds: 200),
// () {
// _blocRole.add(ValidateBasicsStep());
// });
// },
controller: _blocRole.lastNameController,
style: const TextStyle(color: Colors.black),
decoration:
@ -186,13 +189,13 @@ class BasicsView extends StatelessWidget {
padding: const EdgeInsets.all(8.0),
child: TextFormField(
enabled: userId != '' ? false : true,
onChanged: (value) {
Future.delayed(const Duration(milliseconds: 200), () {
_blocRole.add(CheckStepStatus(
isEditUser: userId != '' ? false : true));
_blocRole.add(ValidateBasicsStep());
});
},
// onChanged: (value) {
// Future.delayed(const Duration(milliseconds: 200), () {
// _blocRole.add(CheckStepStatus(
// isEditUser: userId != '' ? false : true));
// _blocRole.add(ValidateBasicsStep());
// });
// },
controller: _blocRole.emailController,
style: const TextStyle(color: ColorsManager.blackColor),
decoration: inputTextFormDeco(hintText: "name@example.com")

View File

@ -11,7 +11,14 @@ class DeleteUserDialog extends StatefulWidget {
}
class _DeleteUserDialogState extends State<DeleteUserDialog> {
int currentStep = 1;
bool isLoading = false;
bool _isDisposed = false;
@override
void dispose() {
_isDisposed = true;
super.dispose();
}
@override
Widget build(BuildContext context) {
@ -56,7 +63,7 @@ class _DeleteUserDialogState extends State<DeleteUserDialog> {
Expanded(
child: InkWell(
onTap: () {
Navigator.of(context).pop(true);
Navigator.of(context).pop(false); // Return false if canceled
},
child: Container(
padding: const EdgeInsets.all(10),
@ -76,7 +83,26 @@ class _DeleteUserDialogState extends State<DeleteUserDialog> {
)),
Expanded(
child: InkWell(
onTap: widget.onTapDelete,
onTap: isLoading
? null
: () async {
setState(() {
isLoading = true;
});
try {
if (widget.onTapDelete != null) {
await widget.onTapDelete!();
}
} finally {
if (!_isDisposed) {
setState(() {
isLoading = false;
});
}
}
Navigator.of(context).pop(true);
},
child: Container(
padding: const EdgeInsets.all(10),
decoration: const BoxDecoration(
@ -91,13 +117,22 @@ class _DeleteUserDialogState extends State<DeleteUserDialog> {
),
),
),
child: const Center(
child: Text(
'Delete',
style: TextStyle(
color: ColorsManager.red,
),
))),
child: Center(
child: isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
color: ColorsManager.red,
strokeWidth: 2.0,
),
)
: const Text(
'Delete',
style: TextStyle(
color: ColorsManager.red,
),
))),
)),
],
)

View File

@ -128,7 +128,7 @@ class _PermissionManagementState extends State<PermissionManagement> {
),
const SizedBox(width: 8),
Text(
option.title,
' ${option.title.isNotEmpty ? option.title[0].toUpperCase() : ''}${option.title.substring(1)}',
style: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w700,
fontSize: 12,
@ -184,7 +184,7 @@ class _PermissionManagementState extends State<PermissionManagement> {
),
const SizedBox(width: 8),
Text(
subOption.title,
' ${subOption.title.isNotEmpty ? subOption.title[0].toUpperCase() : ''}${subOption.title.substring(1)}',
style: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w700,
fontSize: 12,
@ -246,7 +246,7 @@ class _PermissionManagementState extends State<PermissionManagement> {
),
const SizedBox(width: 8),
Text(
child.title,
' ${child.title.isNotEmpty ? child.title[0].toUpperCase() : ''}${child.title.substring(1)}',
style: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400,
fontSize: 12,

View File

@ -5,141 +5,156 @@ import 'package:syncrow_web/utils/style.dart';
Future<void> showPopUpFilterMenu({
required BuildContext context,
Function()? onSortAtoZ,
Function()? onSortZtoA,
required Function(String value) onSortAtoZ,
required Function(String value) onSortZtoA,
Function()? cancelButton,
required Map<String, bool> checkboxStates,
required RelativeRect position,
Function()? onOkPressed,
List<String>? list,
String? isSelected,
}) async {
await showMenu(
context: context,
position:position,
position: position,
color: ColorsManager.whiteColors,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
items: <PopupMenuEntry>[
PopupMenuItem(
onTap: onSortAtoZ,
child: ListTile(
leading: Image.asset(
Assets.AtoZIcon,
width: 25,
),
title: const Text(
"Sort A to Z",
style: TextStyle(color: Colors.blueGrey),
),
),
),
PopupMenuItem(
onTap: onSortZtoA,
child: ListTile(
leading: Image.asset(
Assets.ZtoAIcon,
width: 25,
),
title: const Text(
"Sort Z to A",
style: TextStyle(color: Colors.blueGrey),
),
),
),
const PopupMenuDivider(),
const PopupMenuItem(
child: Text(
"Filter by Status",
style: TextStyle(fontWeight: FontWeight.bold),
)
// Container(
// decoration: containerDecoration.copyWith(
// boxShadow: [],
// borderRadius: const BorderRadius.only(
// topLeft: Radius.circular(10), topRight: Radius.circular(10))),
// child: Padding(
// padding: const EdgeInsets.all(8.0),
// child: TextFormField(
// onChanged: onTextFieldChanged,
// style: const TextStyle(color: Colors.black),
// decoration: textBoxDecoration(radios: 15)!.copyWith(
// fillColor: ColorsManager.whiteColors,
// errorStyle: const TextStyle(height: 0),
// hintStyle: context.textTheme.titleSmall?.copyWith(
// color: Colors.grey,
// fontSize: 12,
// ),
// hintText: 'Search',
// suffixIcon: SizedBox(
// child: SvgPicture.asset(
// Assets.searchIconUser,
// fit: BoxFit.none,
// ),
// ),
// ),
// // "Filter by Status",
// // style: TextStyle(fontWeight: FontWeight.bold),
// ),
// ),
// ),
),
PopupMenuItem(
child: Container(
decoration: containerDecoration.copyWith(
boxShadow: [],
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10))),
padding: const EdgeInsets.all(10),
height: 200,
width: 400,
child: Container(
padding: const EdgeInsets.all(10),
color: Colors.white,
child: ListView.builder(
itemCount: list?.length ?? 0,
itemBuilder: (context, index) {
final item = list![index];
return CheckboxListTile(
dense: true,
title: Text(item),
value: checkboxStates[item],
onChanged: (bool? newValue) {
checkboxStates[item] = newValue ?? false;
(context as Element).markNeedsBuild();
},
);
},
),
),
),
),
PopupMenuItem(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
Navigator.of(context).pop(); // Close the menu
},
child: const Text("Cancel"),
),
GestureDetector(
onTap: onOkPressed,
child: const Text(
"OK",
style: TextStyle(
color: ColorsManager.spaceColor,
enabled: false,
child: StatefulBuilder(
builder: (context, setState) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
child: ListTile(
onTap: () {
setState(() {
if (isSelected == 'Asc') {
isSelected = null;
onSortAtoZ.call('');
} else {
onSortAtoZ.call('Asc');
isSelected = 'Asc';
}
});
},
leading: Image.asset(
Assets.AtoZIcon,
width: 25,
),
title: Text(
"Sort A to Z",
style: TextStyle(
color: isSelected == "Asc"
? ColorsManager.blackColor
: ColorsManager.grayColor),
),
),
),
),
),
],
ListTile(
onTap: () {
setState(() {
if (isSelected == 'Desc') {
isSelected = null;
onSortZtoA.call('');
} else {
onSortZtoA.call('Desc');
isSelected = 'Desc';
}
});
},
leading: Image.asset(
Assets.ZtoAIcon,
width: 25,
),
title: Text(
"Sort Z to A",
style: TextStyle(
color: isSelected == "Desc"
? ColorsManager.blackColor
: ColorsManager.grayColor),
),
),
const Divider(),
const Text(
"Filter by Status",
style: TextStyle(fontWeight: FontWeight.bold),
),
Container(
decoration: containerDecoration.copyWith(
boxShadow: [],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10))),
padding: const EdgeInsets.all(10),
height: 200,
width: 400,
child: Container(
padding: const EdgeInsets.all(10),
color: Colors.white,
child: ListView.builder(
itemCount: list?.length ?? 0,
itemBuilder: (context, index) {
final item = list![index];
return Row(
children: [
Checkbox(
value: checkboxStates[item],
onChanged: (bool? newValue) {
checkboxStates[item] = newValue ?? false;
(context as Element).markNeedsBuild();
},
),
Text(
item,
style: TextStyle(color: ColorsManager.grayColor),
),
],
);
},
),
),
),
const SizedBox(
height: 10,
),
const Divider(),
const SizedBox(
height: 10,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
Navigator.of(context).pop(); // Close the menu
},
child: const Text("Cancel"),
),
GestureDetector(
onTap: onOkPressed,
child: const Text(
"OK",
style: TextStyle(
color: ColorsManager.spaceColor,
),
),
),
],
),
const SizedBox(
height: 10,
),
],
);
},
),
),
],

View File

@ -52,14 +52,16 @@ class _RoleDropdownState extends State<RoleDropdown> {
SizedBox(
child: DropdownButtonFormField<String>(
dropdownColor: ColorsManager.whiteColors,
alignment: Alignment.center,
// alignment: Alignment.,
focusColor: Colors.white,
autofocus: true,
value: selectedRole.isNotEmpty ? selectedRole : null,
items: widget.bloc!.roles.map((role) {
return DropdownMenuItem<String>(
value: role.uuid,
child: Text(role.type),
child: Text(
' ${role.type.isNotEmpty ? role.type[0].toUpperCase() : ''}${role.type.substring(1)}',
),
);
}).toList(),
onChanged: (value) {

View File

@ -93,7 +93,7 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
try {
emit(UsersLoadingState());
bool res = await UserPermissionApi().changeUserStatusById(
event.userId, event.newStatus == "disabled" ? true : false);
event.userId, event.newStatus == "disabled" ? false : true);
if (res == true) {
add(const GetUsers());
// users = users.map((user) {
@ -133,7 +133,10 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
} else {
emit(UsersLoadingState());
currentSortOrder = "Asc";
users.sort((a, b) => a.firstName!.compareTo(b.firstName!));
users.sort((a, b) => a.firstName
.toString()
.toLowerCase()
.compareTo(b.firstName.toString().toLowerCase()));
emit(UsersLoadedState(users: users));
}
}
@ -164,6 +167,7 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
emit(UsersLoadedState(users: users));
} else {
emit(UsersLoadingState());
currentSortOrder = "NewestToOldest";
users.sort((a, b) {
final dateA = _parseDateTime(a.createdDate);
final dateB = _parseDateTime(b.createdDate);
@ -188,6 +192,7 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
final dateB = _parseDateTime(b.createdDate);
return dateA.compareTo(dateB);
});
currentSortOrder = "OldestToNewest";
emit(UsersLoadedState(users: users));
}
}
@ -210,7 +215,7 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
final query = event.query.toLowerCase();
final filteredUsers = initialUsers.where((user) {
final fullName = "${user.firstName} ${user.lastName}".toLowerCase();
final email = user.email.toLowerCase() ;
final email = user.email.toLowerCase();
return fullName.contains(query) || email.contains(query);
}).toList();
emit(UsersLoadedState(users: filteredUsers));
@ -256,49 +261,96 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
void _filterUsersByRole(
FilterUsersByRoleEvent event, Emitter<UserTableState> emit) {
selectedRoles = event.selectedRoles.toSet();
selectedRoles = event.selectedRoles!.toSet();
final filteredUsers = initialUsers.where((user) {
if (selectedRoles.isEmpty) return true;
return selectedRoles.contains(user.roleType);
}).toList();
if (event.sortOrder == "Asc") {
currentSortOrder = "Asc";
filteredUsers.sort((a, b) => a.firstName
.toString()
.toLowerCase()
.compareTo(b.firstName.toString().toLowerCase()));
} else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else {
currentSortOrder = "";
}
emit(UsersLoadedState(users: filteredUsers));
}
void _filterUsersByJobTitle(
FilterUsersByJobEvent event, Emitter<UserTableState> emit) {
selectedJobTitles = event.selectedJob.toSet();
selectedJobTitles = event.selectedJob!.toSet();
emit(UsersLoadingState());
final filteredUsers = initialUsers.where((user) {
if (selectedJobTitles.isEmpty) return true;
return selectedJobTitles.contains(user.jobTitle);
}).toList();
if (event.sortOrder == "Asc") {
currentSortOrder = "Asc";
filteredUsers.sort((a, b) => a.firstName
.toString()
.toLowerCase()
.compareTo(b.firstName.toString().toLowerCase()));
} else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else {
currentSortOrder = "";
}
emit(UsersLoadedState(users: filteredUsers));
}
void _filterUsersByCreated(
FilterUsersByCreatedEvent event, Emitter<UserTableState> emit) {
selectedCreatedBy = event.selectedCreatedBy.toSet();
selectedCreatedBy = event.selectedCreatedBy!.toSet();
final filteredUsers = initialUsers.where((user) {
if (selectedCreatedBy.isEmpty) return true;
return selectedCreatedBy.contains(user.invitedBy);
}).toList();
if (event.sortOrder == "Asc") {
currentSortOrder = "Asc";
filteredUsers.sort((a, b) => a.firstName
.toString()
.toLowerCase()
.compareTo(b.firstName.toString().toLowerCase()));
} else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else {
currentSortOrder = "";
}
emit(UsersLoadedState(users: filteredUsers));
}
void _filterUserStatus(
FilterUsersByDeActevateEvent event, Emitter<UserTableState> emit) {
selectedStatuses = event.selectedActivate.toSet();
selectedStatuses = event.selectedActivate!.toSet();
final filteredUsers = initialUsers.where((user) {
if (selectedStatuses.isEmpty) return true;
return selectedStatuses.contains(user.status);
}).toList();
if (event.sortOrder == "Asc") {
currentSortOrder = "Asc";
filteredUsers.sort((a, b) => a.firstName
.toString()
.toLowerCase()
.compareTo(b.firstName.toString().toLowerCase()));
} else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else {
currentSortOrder = "";
}
emit(UsersLoadedState(users: filteredUsers));
}

View File

@ -89,35 +89,36 @@ class DeleteUserEvent extends UserTableEvent {
}
class FilterUsersByRoleEvent extends UserTableEvent {
final List<String> selectedRoles;
final List<String>? selectedRoles;
final String? sortOrder;
FilterUsersByRoleEvent(this.selectedRoles);
@override
List<Object?> get props => [selectedRoles];
const FilterUsersByRoleEvent({this.selectedRoles, this.sortOrder});
List<Object?> get props => [selectedRoles, sortOrder];
}
class FilterUsersByJobEvent extends UserTableEvent {
final List<String> selectedJob;
final List<String>? selectedJob;
final String? sortOrder;
FilterUsersByJobEvent(this.selectedJob);
@override
List<Object?> get props => [selectedJob];
const FilterUsersByJobEvent({this.selectedJob, this.sortOrder});
List<Object?> get props => [selectedJob, sortOrder];
}
class FilterUsersByCreatedEvent extends UserTableEvent {
final List<String> selectedCreatedBy;
final List<String>? selectedCreatedBy;
FilterUsersByCreatedEvent(this.selectedCreatedBy);
@override
List<Object?> get props => [selectedCreatedBy];
final String? sortOrder;
const FilterUsersByCreatedEvent({this.selectedCreatedBy, this.sortOrder});
List<Object?> get props => [selectedCreatedBy, sortOrder];
}
class FilterUsersByDeActevateEvent extends UserTableEvent {
final List<String> selectedActivate;
final List<String>? selectedActivate;
final String? sortOrder;
FilterUsersByDeActevateEvent(this.selectedActivate);
@override
List<Object?> get props => [selectedActivate];
const FilterUsersByDeActevateEvent({this.selectedActivate, this.sortOrder});
List<Object?> get props => [selectedActivate, sortOrder];
}
class FilterOptionsEvent extends UserTableEvent {

View File

@ -19,19 +19,13 @@ class DynamicTableScreen extends StatefulWidget {
class _DynamicTableScreenState extends State<DynamicTableScreen>
with WidgetsBindingObserver {
late List<double> columnWidths;
late double totalWidth;
// @override
// void initState() {
// super.initState();
// // Initialize column widths with default sizes proportional to the screen width
// // Assigning placeholder values here. The actual sizes will be updated in `build`.
// }
@override
void initState() {
super.initState();
setState(() {
columnWidths = List<double>.filled(widget.titles.length, 150.0);
});
columnWidths = List<double>.filled(widget.titles.length, 150.0);
totalWidth = columnWidths.reduce((a, b) => a + b);
WidgetsBinding.instance.addObserver(this);
}
@ -44,7 +38,6 @@ class _DynamicTableScreenState extends State<DynamicTableScreen>
@override
void didChangeMetrics() {
super.didChangeMetrics();
// Screen size might have changed
final newScreenWidth = MediaQuery.of(context).size.width;
setState(() {
columnWidths = List<double>.generate(widget.titles.length, (index) {
@ -53,7 +46,7 @@ class _DynamicTableScreenState extends State<DynamicTableScreen>
0.12; // 20% of screen width for the second column
} else if (index == 9) {
return newScreenWidth *
0.2; // 25% of screen width for the tenth column
0.1; // 25% of screen width for the tenth column
}
return newScreenWidth *
0.09; // Default to 10% of screen width for other columns
@ -64,293 +57,204 @@ class _DynamicTableScreenState extends State<DynamicTableScreen>
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
// Initialize column widths if they are still set to placeholder values
if (columnWidths.every((width) => width == 120.0)) {
if (columnWidths.every((width) => width == screenWidth * 7)) {
columnWidths = List<double>.generate(widget.titles.length, (index) {
if (index == 1) {
return screenWidth * 0.11;
} else if (index == 9) {
return screenWidth * 0.2;
return screenWidth * 0.1;
}
return screenWidth * 0.11;
return screenWidth * 0.09;
});
setState(() {});
}
return Container(
child: SingleChildScrollView(
clipBehavior: Clip.none,
scrollDirection: Axis.horizontal,
child: Container(
decoration: containerDecoration.copyWith(
color: ColorsManager.whiteColors,
borderRadius: const BorderRadius.all(Radius.circular(20))),
child: FittedBox(
child: Column(
children: [
// Header Row with Resizable Columns
Container(
width: MediaQuery.of(context).size.width,
decoration: containerDecoration.copyWith(
color: ColorsManager.circleRolesBackground,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15))),
child: Row(
children: List.generate(widget.titles.length, (index) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
FittedBox(
child: Container(
padding: const EdgeInsets.only(left: 5, right: 5),
width: columnWidths[index],
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
child: Text(
widget.titles[index],
maxLines: 2,
style: const TextStyle(
overflow: TextOverflow.ellipsis,
fontWeight: FontWeight.w400,
fontSize: 13,
color: ColorsManager.grayColor,
),
return SingleChildScrollView(
clipBehavior: Clip.none,
scrollDirection: Axis.horizontal,
child: Container(
decoration: containerDecoration.copyWith(
color: ColorsManager.whiteColors,
borderRadius: const BorderRadius.all(Radius.circular(20))),
child: FittedBox(
child: Column(
children: [
Container(
width: totalWidth,
decoration: containerDecoration.copyWith(
color: ColorsManager.circleRolesBackground,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(15),
topRight: Radius.circular(15))),
child: Row(
children: List.generate(widget.titles.length, (index) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
FittedBox(
child: Container(
padding: const EdgeInsets.only(left: 5, right: 5),
width: columnWidths[index],
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
child: Text(
widget.titles[index],
maxLines: 2,
style: const TextStyle(
overflow: TextOverflow.ellipsis,
fontWeight: FontWeight.w400,
fontSize: 13,
color: ColorsManager.grayColor,
),
),
if (index != 1 &&
index != 9 &&
index != 8 &&
index != 5)
FittedBox(
child: IconButton(
icon: SvgPicture.asset(
Assets.filterTableIcon,
fit: BoxFit.none,
),
onPressed: () {
if (widget.onFilter != null) {
widget.onFilter!(index);
}
},
),
if (index != 1 &&
index != 9 &&
index != 8 &&
index != 5)
FittedBox(
child: IconButton(
icon: SvgPicture.asset(
Assets.filterTableIcon,
fit: BoxFit.none,
),
)
],
),
),
),
GestureDetector(
onHorizontalDragUpdate: (details) {
setState(() {
columnWidths[index] = (columnWidths[index] +
details.delta.dx)
.clamp(
150.0, 300.0); // Minimum & Maximum size
});
},
child: MouseRegion(
cursor: SystemMouseCursors
.resizeColumn, // Set the cursor to resize
child: Container(
color: Colors.green,
child: Container(
color: ColorsManager.boxDivider,
width: 1,
height: 50, // Height of the header cell
),
),
),
),
],
);
}),
),
),
// Data Rows with Dividers
widget.rows.isEmpty
? Container(
child: SizedBox(
height: MediaQuery.of(context).size.height / 2,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
SvgPicture.asset(Assets.emptyTable),
const SizedBox(
height: 15,
onPressed: () {
if (widget.onFilter != null) {
widget.onFilter!(index);
}
},
),
const Text(
'No Users',
style: TextStyle(
color: ColorsManager.lightGrayColor,
fontSize: 16,
fontWeight: FontWeight.w700),
)
],
),
)
],
),
),
),
)
: Center(
child: Container(
// height: MediaQuery.of(context).size.height * 0.59,
width: MediaQuery.of(context).size.width,
decoration: containerDecoration.copyWith(
color: ColorsManager.whiteColors,
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(15),
bottomRight: Radius.circular(15))),
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.rows.length,
itemBuilder: (context, rowIndex) {
if (columnWidths
.every((width) => width == 120.0)) {
columnWidths = List<double>.generate(
widget.titles.length, (index) {
if (index == 1) {
return screenWidth * 0.11;
} else if (index == 9) {
return screenWidth * 0.2;
}
GestureDetector(
onHorizontalDragUpdate: (details) {
setState(() {
columnWidths[index] =
(columnWidths[index] + details.delta.dx)
.clamp(150.0, 300.0);
totalWidth = columnWidths.reduce((a, b) => a + b);
});
},
child: MouseRegion(
cursor: SystemMouseCursors.resizeColumn,
child: Container(
color: Colors.green,
child: Container(
color: ColorsManager.boxDivider,
width: 1,
height: 50,
),
),
),
),
],
);
}),
),
),
widget.rows.isEmpty
? SizedBox(
height: MediaQuery.of(context).size.height / 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Column(
children: [
SvgPicture.asset(Assets.emptyTable),
const SizedBox(
height: 15,
),
const Text(
'No Users',
style: TextStyle(
color: ColorsManager.lightGrayColor,
fontSize: 16,
fontWeight: FontWeight.w700),
)
],
),
],
),
)
: Center(
child: Container(
width: totalWidth,
decoration: containerDecoration.copyWith(
color: ColorsManager.whiteColors,
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(15),
bottomRight: Radius.circular(15))),
child: ListView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: widget.rows.length,
itemBuilder: (context, rowIndex) {
if (columnWidths.every((width) => width == 120.0)) {
columnWidths = List<double>.generate(
widget.titles.length, (index) {
if (index == 1) {
return screenWidth * 0.11;
});
setState(() {});
}
final row = widget.rows[rowIndex];
return Column(
children: [
Container(
child: Padding(
padding: const EdgeInsets.only(
left: 5,
top: 10,
right: 5,
bottom: 10),
child: Row(
children:
List.generate(row.length, (index) {
return SizedBox(
width: columnWidths[index],
child: SizedBox(
child: Padding(
padding: const EdgeInsets.only(
left: 15, right: 10),
child: row[index],
),
),
);
}),
),
),
),
if (rowIndex < widget.rows.length - 1)
Row(
children: List.generate(
widget.titles.length, (index) {
} else if (index == 9) {
return screenWidth * 0.2;
}
return screenWidth * 0.11;
});
setState(() {});
}
final row = widget.rows[rowIndex];
return Column(
children: [
Container(
child: Padding(
padding: const EdgeInsets.only(
left: 5, top: 10, right: 5, bottom: 10),
child: Row(
children:
List.generate(row.length, (index) {
return SizedBox(
width: columnWidths[index],
child: const Divider(
color: ColorsManager.boxDivider,
thickness: 1,
height: 1,
child: SizedBox(
child: Padding(
padding: const EdgeInsets.only(
left: 15, right: 10),
child: row[index],
),
),
);
}),
),
],
);
},
),
),
),
if (rowIndex < widget.rows.length - 1)
Row(
children: List.generate(
widget.titles.length, (index) {
return SizedBox(
width: columnWidths[index],
child: const Divider(
color: ColorsManager.boxDivider,
thickness: 1,
height: 1,
),
);
}),
),
],
);
},
),
),
],
),
),
],
),
),
),
);
}
}
// Widget build(BuildContext context) {
// return Scaffold(
// body: SingleChildScrollView(
// scrollDirection: Axis.horizontal,
// child: SingleChildScrollView(
// scrollDirection: Axis.vertical,
// child: Column(
// children: [
// // Header Row with Resizable Columns
// Container(
// color: Colors.green,
// child: Row(
// children: List.generate(widget.titles.length, (index) {
// return Row(
// children: [
// Container(
// width: columnWidths[index],
// decoration: const BoxDecoration(
// color: Colors.green,
// ),
// child: Text(
// widget.titles[index],
// style: TextStyle(fontWeight: FontWeight.bold),
// textAlign: TextAlign.center,
// ),
// ),
// GestureDetector(
// onHorizontalDragUpdate: (details) {
// setState(() {
// columnWidths[index] = (columnWidths[index] +
// details.delta.dx)
// .clamp(50.0, 300.0); // Minimum & Maximum size
// });
// },
// child: MouseRegion(
// cursor: SystemMouseCursors
// .resizeColumn, // Set the cursor to resize
// child: Container(
// color: Colors.green,
// child: Container(
// color: Colors.black,
// width: 1,
// height: 50, // Height of the header cell
// ),
// ),
// ),
// ),
// ],
// );
// }),
// ),
// ),
// // Data Rows
// ...widget.rows.map((row) {
// return Row(
// children: List.generate(row.length, (index) {
// return Container(
// width: columnWidths[index],
// child: row[index],
// );
// }),
// );
// }).toList(),
// ],
// ),
// ),
// ),
// );
// }

View File

@ -107,7 +107,6 @@ class UsersPage extends StatelessWidget {
builder: (context, state) {
final screenSize = MediaQuery.of(context).size;
final _blocRole = BlocProvider.of<UserTableBloc>(context);
if (state is UsersLoadingState) {
_blocRole.add(ChangePage(_blocRole.currentPage));
return const Center(child: CircularProgressIndicator());
@ -189,8 +188,6 @@ class UsersPage extends StatelessWidget {
const SizedBox(height: 25),
DynamicTableScreen(
onFilter: (columnIndex) {
_blocRole.add(FilterClearEvent());
if (columnIndex == 0) {
showNameMenu(
context: context,
@ -210,11 +207,12 @@ class UsersPage extends StatelessWidget {
if (columnIndex == 2) {
final Map<String, bool> checkboxStates = {
for (var item in _blocRole.jobTitle)
item: false, // Initialize with false
item: _blocRole.selectedJobTitles.contains(item),
};
final RenderBox overlay = Overlay.of(context)
.context
.findRenderObject() as RenderBox;
showPopUpFilterMenu(
position: RelativeRect.fromLTRB(
overlay.size.width / 4,
@ -225,26 +223,28 @@ class UsersPage extends StatelessWidget {
list: _blocRole.jobTitle,
context: context,
checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder,
onOkPressed: () {
_blocRole.add(FilterClearEvent());
final selectedItems = checkboxStates.entries
.where((entry) => entry.value)
.map((entry) => entry.key)
.toList();
Navigator.of(context).pop();
_blocRole.add(FilterUsersByJobEvent(selectedItems));
_blocRole.add(FilterUsersByJobEvent(
selectedJob: selectedItems,
sortOrder: _blocRole.currentSortOrder,
));
},
onSortAtoZ: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameAsc());
onSortAtoZ: (v) {
_blocRole.currentSortOrder = v;
},
onSortZtoA: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameDesc());
onSortZtoA: (v) {
_blocRole.currentSortOrder = v;
},
);
}
if (columnIndex == 3) {
final Map<String, bool> checkboxStates = {
for (var item in _blocRole.roleTypes)
@ -263,32 +263,31 @@ class UsersPage extends StatelessWidget {
list: _blocRole.roleTypes,
context: context,
checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder,
onOkPressed: () {
_blocRole.add(FilterClearEvent());
final selectedItems = checkboxStates.entries
.where((entry) => entry.value)
.map((entry) => entry.key)
.toList();
Navigator.of(context).pop();
context
.read<UserTableBloc>()
.add(FilterUsersByRoleEvent(selectedItems));
context.read<UserTableBloc>().add(
FilterUsersByRoleEvent(
selectedRoles: selectedItems,
sortOrder: _blocRole.currentSortOrder));
},
onSortAtoZ: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameAsc());
onSortAtoZ: (v) {
_blocRole.currentSortOrder = v;
},
onSortZtoA: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameDesc());
onSortZtoA: (v) {
_blocRole.currentSortOrder = v;
},
);
}
if (columnIndex == 4) {
showDateFilterMenu(
context: context,
isSelected: _blocRole.currentSortOrderDate,
isSelected: _blocRole.currentSortOrder,
aToZTap: () {
context
.read<UserTableBloc>()
@ -319,32 +318,30 @@ class UsersPage extends StatelessWidget {
list: _blocRole.createdBy,
context: context,
checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder,
onOkPressed: () {
_blocRole.add(FilterClearEvent());
final selectedItems = checkboxStates.entries
.where((entry) => entry.value)
.map((entry) => entry.key)
.toList();
Navigator.of(context).pop();
_blocRole
.add(FilterUsersByCreatedEvent(selectedItems));
_blocRole.add(FilterUsersByCreatedEvent(
selectedCreatedBy: selectedItems,
sortOrder: _blocRole.currentSortOrder));
},
onSortAtoZ: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameAsc());
onSortAtoZ: (v) {
_blocRole.currentSortOrder = v;
},
onSortZtoA: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameDesc());
onSortZtoA: (v) {
_blocRole.currentSortOrder = v;
},
);
}
if (columnIndex == 7) {
final Map<String, bool> checkboxStates = {
for (var item in _blocRole.status)
item: _blocRole.selectedCreatedBy.contains(item),
item: _blocRole.selectedStatuses.contains(item),
};
final RenderBox overlay = Overlay.of(context)
.context
@ -359,24 +356,24 @@ class UsersPage extends StatelessWidget {
list: _blocRole.status,
context: context,
checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder,
onOkPressed: () {
_blocRole.add(FilterClearEvent());
final selectedItems = checkboxStates.entries
.where((entry) => entry.value)
.map((entry) => entry.key)
.toList();
Navigator.of(context).pop();
_blocRole
.add(FilterUsersByCreatedEvent(selectedItems));
_blocRole.add(FilterUsersByDeActevateEvent(
selectedActivate: selectedItems,
sortOrder: _blocRole.currentSortOrder));
},
onSortAtoZ: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameAsc());
onSortAtoZ: (v) {
_blocRole.currentSortOrder = v;
},
onSortZtoA: () {
context
.read<UserTableBloc>()
.add(const SortUsersByNameDesc());
onSortZtoA: (v) {
_blocRole.currentSortOrder = v;
},
);
}
@ -412,8 +409,8 @@ class UsersPage extends StatelessWidget {
rows: state.users.map((user) {
return [
Text('${user.firstName} ${user.lastName}'),
Text(user.email ),
Text(user.jobTitle ?? ''),
Text(user.email),
Text(user.jobTitle ?? '-'),
Text(user.roleType ?? ''),
Text(user.createdDate ?? ''),
Text(user.createdTime ?? ''),
@ -476,11 +473,17 @@ class UsersPage extends StatelessWidget {
barrierDismissible: false,
builder: (BuildContext context) {
return DeleteUserDialog(
onTapDelete: () {
onTapDelete: () async {
try {
_blocRole.add(DeleteUserEvent(
user.uuid, context));
},
);
await Future.delayed(
const Duration(seconds: 2));
return true;
} catch (e) {
return false;
}
});
},
).then((v) {
if (v != null) {
@ -504,6 +507,7 @@ class UsersPage extends StatelessWidget {
SizedBox(
width: 500,
child: NumberPagination(
visiblePagesCount: 4,
buttonRadius: 10,
selectedButtonColor: ColorsManager.secondaryColor,
buttonUnSelectedBorderColor:

View File

@ -0,0 +1,74 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_state.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart';
class AddDeviceTypeBloc extends Bloc<AddDeviceTypeEvent, AddDeviceState> {
AddDeviceTypeBloc() : super(AddDeviceInitial()) {
on<InitializeDevice>(_onInitializeTagModels);
on<UpdateProductCountEvent>(_onUpdateProductCount);
}
void _onInitializeTagModels(
InitializeDevice event, Emitter<AddDeviceState> emit) {
emit(AddDeviceLoaded(
selectedProducts: event.addedProducts,
initialTag: event.initialTags,
));
}
void _onUpdateProductCount(
UpdateProductCountEvent event, Emitter<AddDeviceState> emit) {
final currentState = state;
if (currentState is AddDeviceLoaded) {
final existingProduct = currentState.selectedProducts.firstWhere(
(p) => p.productId == event.productId,
orElse: () => SelectedProduct(
productId: event.productId,
count: 0,
productName: event.productName,
product: event.product,
),
);
List<SelectedProduct> updatedProducts;
if (event.count > 0) {
if (!currentState.selectedProducts.contains(existingProduct)) {
updatedProducts = [
...currentState.selectedProducts,
SelectedProduct(
productId: event.productId,
count: event.count,
productName: event.productName,
product: event.product,
),
];
} else {
updatedProducts = currentState.selectedProducts.map((p) {
if (p.productId == event.productId) {
return SelectedProduct(
productId: p.productId,
count: event.count,
productName: p.productName,
product: p.product,
);
}
return p;
}).toList();
}
} else {
// Remove the product if the count is 0
updatedProducts = currentState.selectedProducts
.where((p) => p.productId != event.productId)
.toList();
}
// Emit the updated state
emit(AddDeviceLoaded(
selectedProducts: updatedProducts,
initialTag: currentState.initialTag));
}
}
}

View File

@ -0,0 +1,36 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
abstract class AddDeviceState extends Equatable {
const AddDeviceState();
@override
List<Object> get props => [];
}
class AddDeviceInitial extends AddDeviceState {}
class AddDeviceLoading extends AddDeviceState {}
class AddDeviceLoaded extends AddDeviceState {
final List<SelectedProduct> selectedProducts;
final List<Tag> initialTag;
const AddDeviceLoaded({
required this.selectedProducts,
required this.initialTag,
});
@override
List<Object> get props => [selectedProducts, initialTag];
}
class AddDeviceError extends AddDeviceState {
final String errorMessage;
const AddDeviceError(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}

View File

@ -0,0 +1,41 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
abstract class AddDeviceTypeEvent extends Equatable {
const AddDeviceTypeEvent();
@override
List<Object> get props => [];
}
class UpdateProductCountEvent extends AddDeviceTypeEvent {
final String productId;
final int count;
final String productName;
final ProductModel product;
UpdateProductCountEvent(
{required this.productId,
required this.count,
required this.productName,
required this.product});
@override
List<Object> get props => [productId, count];
}
class InitializeDevice extends AddDeviceTypeEvent {
final List<Tag> initialTags;
final List<SelectedProduct> addedProducts;
const InitializeDevice({
this.initialTags = const [],
required this.addedProducts,
});
@override
List<Object> get props => [initialTags, addedProducts];
}

View File

@ -0,0 +1,151 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_state.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/widgets/scrollable_grid_view_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class AddDeviceTypeWidget extends StatelessWidget {
final List<ProductModel>? products;
final ValueChanged<List<SelectedProduct>>? onProductsSelected;
final List<SelectedProduct>? initialSelectedProducts;
final List<SubspaceModel>? subspaces;
final List<Tag>? spaceTags;
final List<String>? allTags;
final String spaceName;
final bool isCreate;
final Function(List<Tag>, List<SubspaceModel>?)? onSave;
const AddDeviceTypeWidget(
{super.key,
required this.isCreate,
this.products,
this.initialSelectedProducts,
this.onProductsSelected,
this.subspaces,
this.allTags,
this.spaceTags,
this.onSave,
required this.spaceName});
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final crossAxisCount = size.width > 1200
? 8
: size.width > 800
? 5
: 3;
return BlocProvider(
create: (_) => AddDeviceTypeBloc()
..add(InitializeDevice(
initialTags: spaceTags ?? [],
addedProducts: initialSelectedProducts ?? [],
)),
child: Builder(
builder: (context) => AlertDialog(
title: const Text('Add Devices'),
backgroundColor: ColorsManager.whiteColors,
content: BlocBuilder<AddDeviceTypeBloc, AddDeviceState>(
builder: (context, state) {
if (state is AddDeviceLoading) {
return const Center(child: CircularProgressIndicator());
}
if (state is AddDeviceLoaded) {
return SingleChildScrollView(
child: Container(
width: size.width * 0.9,
height: size.height * 0.65,
color: ColorsManager.textFieldGreyColor,
child: Column(
children: [
const SizedBox(height: 16),
Expanded(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20.0),
child: ScrollableGridViewWidget(
initialProductCounts: state.selectedProducts,
products: products,
isCreate: isCreate,
crossAxisCount: crossAxisCount),
),
),
],
),
),
);
}
return const SizedBox();
}),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CancelButton(
label: 'Cancel',
onPressed: () async {
Navigator.of(context).pop();
},
),
SizedBox(
width: 140,
child: BlocBuilder<AddDeviceTypeBloc, AddDeviceState>(
builder: (context, state) {
final isDisabled = state is AddDeviceLoaded &&
state.selectedProducts.isEmpty;
return DefaultButton(
borderRadius: 10,
backgroundColor: ColorsManager.secondaryColor,
foregroundColor: isDisabled
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
onPressed: () async {
if (state is AddDeviceLoaded &&
state.selectedProducts.isNotEmpty) {
final initialTags =
TagHelper.generateInitialForTags(
spaceTags: spaceTags,
subspaces: subspaces,
);
Navigator.of(context).pop();
final dialogTitle = initialTags.isNotEmpty
? 'Edit Device'
: 'Assign Tags';
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (context) => AssignTagDialog(
products: products,
subspaces: subspaces,
addedProducts: state.selectedProducts,
allTags: allTags,
spaceName: spaceName,
initialTags: initialTags,
title: dialogTitle,
onSave: onSave),
);
}
},
child: const Text('Next'),
);
},
)),
],
),
],
),
));
}
}

View File

@ -0,0 +1,69 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_type_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/counter_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/widgets/device_icon_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/widgets/device_name_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
class DeviceTypeTileWidget extends StatelessWidget {
final ProductModel product;
final List<SelectedProduct> productCounts;
final bool isCreate;
const DeviceTypeTileWidget(
{super.key,
required this.product,
required this.productCounts,
required this.isCreate});
@override
Widget build(BuildContext context) {
final selectedProduct = productCounts.firstWhere(
(p) => p.productId == product.uuid,
orElse: () => SelectedProduct(
productId: product.uuid,
count: 0,
productName: product.catName,
product: product),
);
return Card(
elevation: 2,
color: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
DeviceIconWidget(icon: product.icon ?? Assets.doorSensor),
const SizedBox(height: 4),
DeviceNameWidget(name: product.name),
const SizedBox(height: 4),
CounterWidget(
isCreate: isCreate,
initialCount: selectedProduct.count,
onCountChanged: (newCount) {
context.read<AddDeviceTypeBloc>().add(
UpdateProductCountEvent(
productId: product.uuid,
count: newCount,
productName: product.catName,
product: product),
);
},
),
],
),
),
);
}
}

View File

@ -0,0 +1,76 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/bloc/add_device_state.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/widgets/device_type_tile_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
class ScrollableGridViewWidget extends StatelessWidget {
final List<ProductModel>? products;
final int crossAxisCount;
final List<SelectedProduct>? initialProductCounts;
final bool isCreate;
const ScrollableGridViewWidget(
{super.key,
required this.products,
required this.crossAxisCount,
this.initialProductCounts,
required this.isCreate});
@override
Widget build(BuildContext context) {
final scrollController = ScrollController();
return Scrollbar(
controller: scrollController,
thumbVisibility: true,
child: BlocBuilder<AddDeviceTypeBloc, AddDeviceState>(
builder: (context, state) {
final productCounts = state is AddDeviceLoaded
? state.selectedProducts
: <SelectedProduct>[];
return GridView.builder(
controller: scrollController,
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
mainAxisSpacing: 6,
crossAxisSpacing: 4,
childAspectRatio: .8,
),
itemCount: products?.length ?? 0,
itemBuilder: (context, index) {
final product = products![index];
final initialProductCount = _findInitialProductCount(product);
return DeviceTypeTileWidget(
product: product,
isCreate: isCreate,
productCounts: initialProductCount != null
? [...productCounts, initialProductCount]
: productCounts,
);
},
);
},
),
);
}
SelectedProduct? _findInitialProductCount(ProductModel product) {
if (initialProductCounts == null) return null;
final matchingProduct = initialProductCounts!.firstWhere(
(selectedProduct) => selectedProduct.productId == product.uuid,
orElse: () => SelectedProduct(
productId: '',
count: 0,
productName: '',
product: null,
),
);
return matchingProduct.productId.isNotEmpty ? matchingProduct : null;
}
}

View File

@ -1,13 +1,19 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/create_subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_state.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_body_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart';
import 'package:syncrow_web/services/product_api.dart';
import 'package:syncrow_web/services/space_mana_api.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';
class SpaceManagementBloc
extends Bloc<SpaceManagementEvent, SpaceManagementState> {
@ -52,10 +58,14 @@ class SpaceManagementBloc
break;
}
}
var prevSpaceModels = await fetchSpaceModels(previousState);
emit(SpaceManagementLoaded(
communities: updatedCommunities,
products: previousState.products,
selectedCommunity: previousState.selectedCommunity,
spaceModels: prevSpaceModels,
));
}
} else {
@ -66,6 +76,42 @@ class SpaceManagementBloc
}
}
Future<List<SpaceTemplateModel>> fetchSpaceModels(
SpaceManagementState previousState) async {
try {
List<SpaceTemplateModel> allSpaces = [];
List<SpaceTemplateModel> prevSpaceModels = [];
if (previousState is SpaceManagementLoaded ||
previousState is BlankState) {
prevSpaceModels = List<SpaceTemplateModel>.from(
(previousState as dynamic).spaceModels ?? [],
);
allSpaces.addAll(prevSpaceModels);
}
if (prevSpaceModels.isEmpty) {
bool hasNext = true;
int page = 1;
while (hasNext) {
final spaces = await _spaceModelApi.listSpaceModels(page: page);
if (spaces.isNotEmpty) {
allSpaces.addAll(spaces);
page++;
} else {
hasNext = false;
}
}
prevSpaceModels = await _spaceModelApi.listSpaceModels(page: 1);
}
return allSpaces;
} catch (e) {
return [];
}
}
void _onloadProducts() async {
if (_cachedProducts == null) {
final products = await _productApi.fetchProducts();
@ -89,19 +135,24 @@ class SpaceManagementBloc
return await _api.getSpaceHierarchy(communityUuid);
}
void _onNewCommunity(
Future<void> _onNewCommunity(
NewCommunityEvent event,
Emitter<SpaceManagementState> emit,
) {
) async {
try {
final previousState = state;
if (event.communities.isEmpty) {
emit(const SpaceManagementError('No communities provided.'));
return;
}
var prevSpaceModels = await fetchSpaceModels(previousState);
emit(BlankState(
communities: event.communities,
products: _cachedProducts ?? [],
spaceModels: prevSpaceModels,
));
} catch (error) {
emit(SpaceManagementError('Error loading communities: $error'));
@ -112,6 +163,7 @@ class SpaceManagementBloc
BlankStateEvent event, Emitter<SpaceManagementState> emit) async {
try {
final previousState = state;
var prevSpaceModels = await fetchSpaceModels(previousState);
if (previousState is SpaceManagementLoaded ||
previousState is BlankState) {
@ -119,6 +171,7 @@ class SpaceManagementBloc
emit(BlankState(
communities: List<CommunityModel>.from(prevCommunities),
products: _cachedProducts ?? [],
spaceModels: prevSpaceModels,
));
return;
}
@ -127,6 +180,7 @@ class SpaceManagementBloc
final updatedCommunities =
await Future.wait(communities.map((community) async {
final spaces = await _fetchSpacesForCommunity(community.uuid);
return CommunityModel(
uuid: community.uuid,
createdAt: community.createdAt,
@ -139,6 +193,7 @@ class SpaceManagementBloc
}));
emit(BlankState(
spaceModels: prevSpaceModels,
communities: updatedCommunities,
products: _cachedProducts ?? [],
));
@ -151,6 +206,7 @@ class SpaceManagementBloc
LoadCommunityAndSpacesEvent event,
Emitter<SpaceManagementState> emit,
) async {
var prevState = state;
emit(SpaceManagementLoading());
try {
_onloadProducts();
@ -172,8 +228,11 @@ class SpaceManagementBloc
}).toList(),
);
final prevSpaceModels = await fetchSpaceModels(prevState);
emit(SpaceManagementLoaded(
communities: updatedCommunities, products: _cachedProducts ?? []));
communities: updatedCommunities,
products: _cachedProducts ?? [],
spaceModels: prevSpaceModels));
} catch (e) {
emit(SpaceManagementError('Error loading communities and spaces: $e'));
}
@ -213,6 +272,7 @@ class SpaceManagementBloc
try {
CommunityModel? newCommunity =
await _api.createCommunity(event.name, event.description);
var prevSpaceModels = await fetchSpaceModels(previousState);
if (newCommunity != null) {
if (previousState is SpaceManagementLoaded ||
@ -222,6 +282,7 @@ class SpaceManagementBloc
);
final updatedCommunities = prevCommunities..add(newCommunity);
emit(SpaceManagementLoaded(
spaceModels: prevSpaceModels,
communities: updatedCommunities,
products: _cachedProducts ?? [],
selectedCommunity: newCommunity,
@ -276,12 +337,16 @@ class SpaceManagementBloc
final communities = List<CommunityModel>.from(
(previousState as dynamic).communities,
);
final spaceModels = List<SpaceTemplateModel>.from(
(previousState as dynamic).spaceModels,
);
emit(SpaceManagementLoaded(
communities: communities,
products: _cachedProducts ?? [],
selectedCommunity: selectedCommunity,
selectedSpace: selectedSpace,
));
communities: communities,
products: _cachedProducts ?? [],
selectedCommunity: selectedCommunity,
selectedSpace: selectedSpace,
spaceModels: spaceModels));
}
} catch (e) {
emit(SpaceManagementError('Error updating state: $e'));
@ -304,7 +369,7 @@ class SpaceManagementBloc
emit(SpaceCreationSuccess(spaces: updatedSpaces));
if (previousState is SpaceManagementLoaded) {
_updateLoadedState(
await _updateLoadedState(
previousState,
allSpaces,
event.communityUuid,
@ -322,23 +387,25 @@ class SpaceManagementBloc
}
}
void _updateLoadedState(
Future<void> _updateLoadedState(
SpaceManagementLoaded previousState,
List<SpaceModel> allSpaces,
String communityUuid,
Emitter<SpaceManagementState> emit,
) {
) async {
var prevSpaceModels = await fetchSpaceModels(previousState);
final communities = List<CommunityModel>.from(previousState.communities);
for (var community in communities) {
if (community.uuid == communityUuid) {
community.spaces = allSpaces;
emit(SpaceManagementLoaded(
communities: communities,
products: _cachedProducts ?? [],
selectedCommunity: community,
selectedSpace: null,
));
communities: communities,
products: _cachedProducts ?? [],
selectedCommunity: community,
selectedSpace: null,
spaceModels: prevSpaceModels));
return;
}
}
@ -358,13 +425,84 @@ class SpaceManagementBloc
await _api.deleteSpace(communityUuid, parent.uuid!);
}
} catch (e) {
rethrow; // Decide whether to stop execution or continue
rethrow;
}
}
orderedSpaces.removeWhere((space) => parentsToDelete.contains(space));
for (var space in orderedSpaces) {
try {
if (space.uuid != null && space.uuid!.isNotEmpty) {
List<TagModelUpdate> tagUpdates = [];
final prevSpace = await _api.getSpace(communityUuid, space.uuid!);
final List<UpdateSubspaceTemplateModel> subspaceUpdates = [];
final List<SubspaceModel>? prevSubspaces = prevSpace?.subspaces;
final List<SubspaceModel>? newSubspaces = space.subspaces;
tagUpdates = processTagUpdates(prevSpace?.tags, space.tags);
if (prevSubspaces != null || newSubspaces != null) {
if (prevSubspaces != null && newSubspaces != null) {
for (var prevSubspace in prevSubspaces) {
final existsInNew = newSubspaces
.any((subspace) => subspace.uuid == prevSubspace.uuid);
if (!existsInNew) {
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.delete, uuid: prevSubspace.uuid));
}
}
} else if (prevSubspaces != null && newSubspaces == null) {
for (var prevSubspace in prevSubspaces) {
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.delete, uuid: prevSubspace.uuid));
}
}
if (newSubspaces != null) {
for (var newSubspace in newSubspaces) {
// Tag without UUID
if ((newSubspace.uuid == null || newSubspace.uuid!.isEmpty)) {
final List<TagModelUpdate> tagUpdates = [];
if (newSubspace.tags != null) {
for (var tag in newSubspace.tags!) {
tagUpdates.add(TagModelUpdate(
action: Action.add,
uuid: tag.uuid == '' ? null : tag.uuid,
tag: tag.tag,
productUuid: tag.product?.uuid));
}
}
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.add,
subspaceName: newSubspace.subspaceName,
tags: tagUpdates));
}
}
}
if (prevSubspaces != null && newSubspaces != null) {
final newSubspaceMap = {
for (var subspace in newSubspaces) subspace.uuid: subspace
};
for (var prevSubspace in prevSubspaces) {
final newSubspace = newSubspaceMap[prevSubspace.uuid];
if (newSubspace != null) {
final List<TagModelUpdate> tagSubspaceUpdates =
processTagUpdates(prevSubspace.tags, newSubspace.tags);
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.update,
uuid: newSubspace.uuid,
subspaceName: newSubspace.subspaceName,
tags: tagSubspaceUpdates));
}
}
}
}
final response = await _api.updateSpace(
communityId: communityUuid,
spaceId: space.uuid!,
@ -373,10 +511,27 @@ class SpaceManagementBloc
isPrivate: space.isPrivate,
position: space.position,
icon: space.icon,
subspaces: subspaceUpdates,
tags: tagUpdates,
direction: space.incomingConnection?.direction,
);
} else {
// Call create if the space does not have a UUID
final List<CreateTagBodyModel> tagBodyModels = space.tags != null
? space.tags!.map((tag) => tag.toCreateTagBodyModel()).toList()
: [];
final createSubspaceBodyModels = space.subspaces?.map((subspace) {
final tagBodyModels = subspace.tags
?.map((tag) => tag.toCreateTagBodyModel())
.toList() ??
[];
return CreateSubspaceModel()
..subspaceName = subspace.subspaceName
..tags = tagBodyModels;
}).toList() ??
[];
final response = await _api.createSpace(
communityId: communityUuid,
name: space.name,
@ -385,6 +540,9 @@ class SpaceManagementBloc
position: space.position,
icon: space.icon,
direction: space.incomingConnection?.direction,
spaceModelUuid: space.spaceModel?.uuid,
tags: tagBodyModels,
subspaces: createSubspaceBodyModels,
);
space.uuid = response?.uuid;
}
@ -424,6 +582,8 @@ class SpaceManagementBloc
SpaceModelLoadEvent event, Emitter<SpaceManagementState> emit) async {
emit(SpaceManagementLoading());
try {
var prevState = state;
List<CommunityModel> communities = await _api.fetchCommunities();
List<CommunityModel> updatedCommunities = await Future.wait(
@ -442,14 +602,89 @@ class SpaceManagementBloc
}).toList(),
);
List<SpaceTemplateModel> spaceModels =
await _spaceModelApi.listSpaceModels(page: 1);
var prevSpaceModels = await fetchSpaceModels(prevState);
emit(SpaceModelLoaded(
communities: updatedCommunities,
products: _cachedProducts ?? [],
spaceModels: spaceModels));
spaceModels: prevSpaceModels));
} catch (e) {
emit(SpaceManagementError('Error loading communities and spaces: $e'));
}
}
List<TagModelUpdate> processTagUpdates(
List<Tag>? prevTags,
List<Tag>? newTags,
) {
final List<TagModelUpdate> tagUpdates = [];
final processedTags = <String?>{};
if (prevTags == null && newTags != null) {
for (var newTag in newTags) {
tagUpdates.add(TagModelUpdate(
action: Action.add,
tag: newTag.tag,
uuid: newTag.uuid,
productUuid: newTag.product?.uuid,
));
}
return tagUpdates;
}
if (newTags != null || prevTags != null) {
// Case 1: Tags deleted
if (prevTags != null && newTags != null) {
for (var prevTag in prevTags) {
final existsInNew =
newTags.any((newTag) => newTag.uuid == prevTag.uuid);
if (!existsInNew) {
tagUpdates
.add(TagModelUpdate(action: Action.delete, uuid: prevTag.uuid));
}
}
} else if (prevTags != null && newTags == null) {
for (var prevTag in prevTags) {
tagUpdates
.add(TagModelUpdate(action: Action.delete, uuid: prevTag.uuid));
}
}
// Case 2: Tags added
if (newTags != null) {
final prevTagUuids = prevTags?.map((t) => t.uuid).toSet() ?? {};
for (var newTag in newTags) {
// Tag without UUID
if ((newTag.uuid == null || !prevTagUuids.contains(newTag.uuid)) &&
!processedTags.contains(newTag.tag)) {
tagUpdates.add(TagModelUpdate(
action: Action.add,
tag: newTag.tag,
uuid: newTag.uuid == '' ? null : newTag.uuid,
productUuid: newTag.product?.uuid));
processedTags.add(newTag.tag);
}
}
}
// Case 3: Tags updated
if (prevTags != null && newTags != null) {
final newTagMap = {for (var tag in newTags) tag.uuid: tag};
for (var prevTag in prevTags) {
final newTag = newTagMap[prevTag.uuid];
if (newTag != null) {
tagUpdates.add(TagModelUpdate(
action: Action.update,
uuid: newTag.uuid,
tag: newTag.tag,
));
} else {}
}
}
}
return tagUpdates;
}
}

View File

@ -20,12 +20,14 @@ class SpaceManagementLoaded extends SpaceManagementState {
final List<ProductModel> products;
CommunityModel? selectedCommunity;
SpaceModel? selectedSpace;
List<SpaceTemplateModel>? spaceModels;
SpaceManagementLoaded(
{required this.communities,
required this.products,
this.selectedCommunity,
this.selectedSpace});
this.selectedSpace,
this.spaceModels});
}
class SpaceModelManagenetLoaded extends SpaceManagementState {
@ -35,11 +37,10 @@ class SpaceModelManagenetLoaded extends SpaceManagementState {
class BlankState extends SpaceManagementState {
final List<CommunityModel> communities;
final List<ProductModel> products;
List<SpaceTemplateModel>? spaceModels;
BlankState({
required this.communities,
required this.products,
});
BlankState(
{required this.communities, required this.products, this.spaceModels});
}
class SpaceCreationSuccess extends SpaceManagementState {
@ -61,7 +62,7 @@ class SpaceManagementError extends SpaceManagementState {
}
class SpaceModelLoaded extends SpaceManagementState {
final List<SpaceTemplateModel> spaceModels;
List<SpaceTemplateModel> spaceModels;
final List<ProductModel> products;
final List<CommunityModel> communities;

View File

@ -0,0 +1,26 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:uuid/uuid.dart';
abstract class BaseTag {
String? uuid;
String? tag;
final ProductModel? product;
String internalId;
String? location;
BaseTag({
this.uuid,
required this.tag,
this.product,
String? internalId,
this.location,
}) : internalId = internalId ?? const Uuid().v4();
Map<String, dynamic> toJson();
BaseTag copyWith({
String? tag,
ProductModel? product,
String? location,
String? internalId,
});
}

View File

@ -0,0 +1,13 @@
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_body_model.dart';
class CreateSubspaceModel {
late String subspaceName;
late List<CreateTagBodyModel>? tags;
Map<String, dynamic> toJson() {
return {
'subspaceName': subspaceName,
'tags': tags?.map((tag) => tag.toJson()).toList(),
};
}
}

View File

@ -66,4 +66,25 @@ class ProductModel {
String toString() {
return 'ProductModel(uuid: $uuid, catName: $catName, prodId: $prodId, prodType: $prodType, name: $name, icon: $icon)';
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ProductModel &&
runtimeType == other.runtimeType &&
uuid == other.uuid &&
catName == other.catName &&
prodId == other.prodId &&
prodType == other.prodType &&
name == other.name &&
icon == other.icon;
@override
int get hashCode =>
uuid.hashCode ^
catName.hashCode ^
prodId.hashCode ^
prodType.hashCode ^
name.hashCode ^
icon.hashCode;
}

View File

@ -1,11 +1,13 @@
import 'dart:ui';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/connection_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:uuid/uuid.dart';
enum SpaceStatus { newSpace, modified, unchanged, deleted }
enum SpaceStatus { newSpace, modified, unchanged, deleted, parentDeleted }
class SpaceModel {
String? uuid;
@ -21,6 +23,9 @@ class SpaceModel {
bool isHovered;
SpaceStatus status;
String internalId;
SpaceTemplateModel? spaceModel;
List<Tag>? tags;
List<SubspaceModel>? subspaces;
List<Connection> outgoingConnections = []; // Connections from this space
Connection? incomingConnection; // Connections to this space
@ -40,6 +45,9 @@ class SpaceModel {
this.isHovered = false,
this.incomingConnection,
this.status = SpaceStatus.unchanged,
this.spaceModel,
this.tags,
this.subspaces,
}) : internalId = internalId ?? const Uuid().v4();
factory SpaceModel.fromJson(Map<String, dynamic> json,
@ -58,10 +66,14 @@ class SpaceModel {
final instance = SpaceModel(
internalId: internalId,
uuid: json['uuid'] ?? '',
spaceTuyaUuid: json['spaceTuyaUuid'],
name: json['spaceName'],
isPrivate: json['isPrivate'] ?? false,
invitationCode: json['invitationCode'],
subspaces: (json['subspaces'] as List<dynamic>?)
?.where((e) => e is Map<String, dynamic>) // Validate type
.map((e) => SubspaceModel.fromJson(e as Map<String, dynamic>))
.toList() ??
[],
parent: parentInternalId != null
? SpaceModel(
internalId: parentInternalId,
@ -83,6 +95,14 @@ class SpaceModel {
icon: json['icon'] ?? Assets.location,
position: Offset(json['x'] ?? 0, json['y'] ?? 0),
isHovered: false,
spaceModel: json['spaceModel'] != null
? SpaceTemplateModel.fromJson(json['spaceModel'])
: null,
tags: (json['tags'] as List<dynamic>?)
?.where((item) => item is Map<String, dynamic>) // Validate type
.map((item) => Tag.fromJson(item as Map<String, dynamic>))
.toList() ??
[],
);
if (json['incomingConnections'] != null &&
@ -108,6 +128,7 @@ class SpaceModel {
'isPrivate': isPrivate,
'invitationCode': invitationCode,
'parent': parent?.uuid,
'subspaces': subspaces?.map((e) => e.toJson()).toList(),
'community': community?.toMap(),
'children': children.map((child) => child.toMap()).toList(),
'icon': icon,
@ -115,6 +136,7 @@ class SpaceModel {
'isHovered': isHovered,
'outgoingConnections': outgoingConnections.map((c) => c.toMap()).toList(),
'incomingConnection': incomingConnection?.toMap(),
'tags': tags?.map((e) => e.toJson()).toList(),
};
}
@ -122,3 +144,28 @@ class SpaceModel {
outgoingConnections.add(connection);
}
}
extension SpaceExtensions on SpaceModel {
List<String> listAllTagValues() {
final List<String> tagValues = [];
if (tags != null) {
tagValues.addAll(
tags!.map((tag) => tag.tag ?? '').where((tag) => tag.isNotEmpty));
}
if (subspaces != null) {
for (final subspace in subspaces!) {
if (subspace.tags != null) {
tagValues.addAll(
subspace.tags!
.map((tag) => tag.tag ?? '')
.where((tag) => tag.isNotEmpty),
);
}
}
}
return tagValues;
}
}

View File

@ -0,0 +1,116 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';
import 'package:uuid/uuid.dart';
import 'tag.dart';
class SubspaceModel {
final String? uuid;
String subspaceName;
final bool disabled;
List<Tag>? tags;
String internalId;
SubspaceModel({
this.uuid,
required this.subspaceName,
required this.disabled,
this.tags,
String? internalId,
}) : internalId = internalId ?? const Uuid().v4();
factory SubspaceModel.fromJson(Map<String, dynamic> json) {
final String internalId = json['internalId'] ?? const Uuid().v4();
return SubspaceModel(
uuid: json['uuid'] ?? '',
subspaceName: json['subspaceName'] ?? '',
disabled: json['disabled'] ?? false,
internalId: internalId,
tags: (json['tags'] as List<dynamic>?)
?.map((item) => Tag.fromJson(item))
.toList() ??
[],
);
}
Map<String, dynamic> toJson() {
return {
'uuid': uuid,
'subspaceName': subspaceName,
'disabled': disabled,
'tags': tags?.map((e) => e.toJson()).toList() ?? [],
};
}
}
class UpdateSubspaceModel {
final String uuid;
final Action action;
final String? subspaceName;
final List<UpdateTag>? tags;
UpdateSubspaceModel({
required this.action,
required this.uuid,
this.subspaceName,
this.tags,
});
factory UpdateSubspaceModel.fromJson(Map<String, dynamic> json) {
return UpdateSubspaceModel(
action: ActionExtension.fromValue(json['action']),
uuid: json['uuid'] ?? '',
subspaceName: json['subspaceName'] ?? '',
tags: (json['tags'] as List)
.map((item) => UpdateTag.fromJson(item))
.toList(),
);
}
Map<String, dynamic> toJson() {
return {
'action': action.value,
'uuid': uuid,
'subspaceName': subspaceName,
'tags': tags?.map((e) => e.toJson()).toList() ?? [],
};
}
}
class UpdateTag {
final Action action;
final String? uuid;
final String tag;
final bool disabled;
final ProductModel? product;
UpdateTag({
required this.action,
this.uuid,
required this.tag,
required this.disabled,
this.product,
});
factory UpdateTag.fromJson(Map<String, dynamic> json) {
return UpdateTag(
action: ActionExtension.fromValue(json['action']),
uuid: json['uuid'] ?? '',
tag: json['tag'] ?? '',
disabled: json['disabled'] ?? false,
product: json['product'] != null
? ProductModel.fromMap(json['product'])
: null,
);
}
Map<String, dynamic> toJson() {
return {
'action': action.value,
'uuid': uuid,
'tag': tag,
'disabled': disabled,
'product': product?.toMap(),
};
}
}

View File

@ -0,0 +1,73 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/base_tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/create_space_template_body_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_body_model.dart';
import 'package:uuid/uuid.dart';
class Tag extends BaseTag {
Tag({
String? uuid,
required String? tag,
ProductModel? product,
String? internalId,
String? location,
}) : super(
uuid: uuid,
tag: tag,
product: product,
internalId: internalId,
location: location,
);
factory Tag.fromJson(Map<String, dynamic> json) {
final String internalId = json['internalId'] ?? const Uuid().v4();
return Tag(
uuid: json['uuid'] ?? '',
internalId: internalId,
tag: json['tag'] ?? '',
product: json['product'] != null
? ProductModel.fromMap(json['product'])
: null,
);
}
@override
Tag copyWith({
String? tag,
ProductModel? product,
String? location,
String? internalId,
}) {
return Tag(
uuid: uuid,
tag: tag ?? this.tag,
product: product ?? this.product,
location: location ?? this.location,
internalId: internalId ?? this.internalId,
);
}
Map<String, dynamic> toJson() {
return {
'uuid': uuid,
'tag': tag,
'product': product?.toMap(),
};
}
}
extension TagModelExtensions on Tag {
TagBodyModel toTagBodyModel() {
return TagBodyModel()
..uuid = uuid ?? ''
..tag = tag ?? ''
..productUuid = product?.uuid;
}
CreateTagBodyModel toCreateTagBodyModel() {
return CreateTagBodyModel()
..tag = tag ?? ''
..productUuid = product?.uuid;
}
}

View File

@ -51,6 +51,7 @@ class SpaceManagementPageState extends State<SpaceManagementPage> {
selectedCommunity: null,
selectedSpace: null,
products: state.products,
shouldNavigateToSpaceModelPage: false,
);
} else if (state is SpaceManagementLoaded) {
return LoadedSpaceView(
@ -58,12 +59,16 @@ class SpaceManagementPageState extends State<SpaceManagementPage> {
selectedCommunity: state.selectedCommunity,
selectedSpace: state.selectedSpace,
products: state.products,
spaceModels: state.spaceModels,
shouldNavigateToSpaceModelPage: false,
);
} else if (state is SpaceModelLoaded) {
return LoadedSpaceView(
communities: state.communities,
products: state.products,
spaceModels: state.spaceModels);
communities: state.communities,
products: state.products,
spaceModels: state.spaceModels,
shouldNavigateToSpaceModelPage: true,
);
} else if (state is SpaceManagementError) {
return Center(child: Text('Error: ${state.errorMessage}'));
}

View File

@ -137,6 +137,7 @@ class _AddDeviceWidgetState extends State<AddDeviceWidget> {
_buildDeviceName(product, size),
const SizedBox(height: 4),
CounterWidget(
isCreate: false,
initialCount: selectedProduct.count,
onCountChanged: (newCount) {
setState(() {

View File

@ -0,0 +1,68 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/community_structure_header_button.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
class CommunityStructureHeaderActionButtons extends StatelessWidget {
const CommunityStructureHeaderActionButtons(
{super.key,
required this.theme,
required this.isSave,
required this.onSave,
required this.onDelete,
required this.selectedSpace,
required this.onDuplicate,
required this.onEdit});
final ThemeData theme;
final bool isSave;
final VoidCallback onSave;
final VoidCallback onDelete;
final VoidCallback onDuplicate;
final VoidCallback onEdit;
final SpaceModel? selectedSpace;
@override
Widget build(BuildContext context) {
final canShowActions = selectedSpace != null &&
selectedSpace?.status != SpaceStatus.deleted &&
selectedSpace?.status != SpaceStatus.parentDeleted;
return Wrap(
alignment: WrapAlignment.end,
spacing: 10,
children: [
if (isSave)
CommunityStructureHeaderButton(
label: "Save",
icon: const Icon(Icons.save,
size: 18, color: ColorsManager.spaceColor),
onPressed: onSave,
theme: theme,
),
if (canShowActions) ...[
CommunityStructureHeaderButton(
label: "Edit",
svgAsset: Assets.editSpace,
onPressed: onEdit,
theme: theme,
),
CommunityStructureHeaderButton(
label: "Duplicate",
svgAsset: Assets.duplicate,
onPressed: onDuplicate,
theme: theme,
),
CommunityStructureHeaderButton(
label: "Delete",
svgAsset: Assets.spaceDelete,
onPressed: onDelete,
theme: theme,
),
],
],
);
}
}

View File

@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class CommunityStructureHeaderButton extends StatelessWidget {
const CommunityStructureHeaderButton({
super.key,
required this.label,
this.icon,
required this.onPressed,
this.svgAsset,
required this.theme,
});
final String label;
final Widget? icon;
final VoidCallback onPressed;
final String? svgAsset;
final ThemeData theme;
@override
Widget build(BuildContext context) {
const double buttonHeight = 40;
return ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: 130,
minHeight: buttonHeight,
),
child: DefaultButton(
onPressed: onPressed,
borderWidth: 2,
backgroundColor: ColorsManager.textFieldGreyColor,
foregroundColor: ColorsManager.blackColor,
borderRadius: 12.0,
padding: 2.0,
height: buttonHeight,
elevation: 0,
borderColor: ColorsManager.lightGrayColor,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null) icon!,
if (svgAsset != null)
SvgPicture.asset(
svgAsset!,
width: 20,
height: 20,
),
const SizedBox(width: 10),
Flexible(
child: Text(
label,
style: theme.textTheme.bodySmall
?.copyWith(color: ColorsManager.blackColor, fontSize: 14),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
],
),
),
);
}
}

View File

@ -1,7 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/community_structure_header_action_button.dart';
import 'package:syncrow_web/pages/spaces_management/create_community/view/create_community_dialog.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
@ -13,10 +14,14 @@ class CommunityStructureHeader extends StatefulWidget {
final TextEditingController nameController;
final VoidCallback onSave;
final VoidCallback onDelete;
final VoidCallback onEdit;
final VoidCallback onDuplicate;
final VoidCallback onEditName;
final ValueChanged<String> onNameSubmitted;
final List<CommunityModel> communities;
final CommunityModel? community;
final SpaceModel? selectedSpace;
const CommunityStructureHeader(
{super.key,
@ -29,7 +34,10 @@ class CommunityStructureHeader extends StatefulWidget {
required this.onEditName,
required this.onNameSubmitted,
this.community,
required this.communities});
required this.communities,
this.selectedSpace,
required this.onDuplicate,
required this.onEdit});
@override
State<CommunityStructureHeader> createState() =>
@ -137,65 +145,19 @@ class _CommunityStructureHeaderState extends State<CommunityStructureHeader> {
],
),
),
if (widget.isSave) ...[
const SizedBox(width: 8),
_buildActionButtons(theme),
],
const SizedBox(width: 8),
CommunityStructureHeaderActionButtons(
theme: theme,
isSave: widget.isSave,
onSave: widget.onSave,
onDelete: widget.onDelete,
onDuplicate: widget.onDuplicate,
onEdit: widget.onEdit,
selectedSpace: widget.selectedSpace,
),
],
),
],
);
}
Widget _buildActionButtons(ThemeData theme) {
return Wrap(
alignment: WrapAlignment.end,
spacing: 10,
children: [
_buildButton(
label: "Save",
icon: const Icon(Icons.save,
size: 18, color: ColorsManager.spaceColor),
onPressed: widget.onSave,
theme: theme),
],
);
}
Widget _buildButton(
{required String label,
required Widget icon,
required VoidCallback onPressed,
required ThemeData theme}) {
const double buttonHeight = 30;
return ConstrainedBox(
constraints: BoxConstraints(maxWidth: 80, minHeight: buttonHeight),
child: DefaultButton(
onPressed: onPressed,
backgroundColor: ColorsManager.textFieldGreyColor,
foregroundColor: ColorsManager.blackColor,
borderRadius: 8.0,
padding: 2.0,
height: buttonHeight,
elevation: 0,
borderColor: ColorsManager.lightGrayColor,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
icon,
const SizedBox(width: 5),
Flexible(
child: Text(
label,
style: theme.textTheme.bodySmall
?.copyWith(color: ColorsManager.blackColor),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
],
),
),
);
}
}

View File

@ -4,6 +4,8 @@ import 'package:flutter_bloc/flutter_bloc.dart';
// Syncrow project imports
import 'package:syncrow_web/pages/common/buttons/add_space_button.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
@ -11,12 +13,19 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_pr
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/connection_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/blank_community_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/community_structure_header_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/create_space_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/curved_line_painter.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/duplicate_process_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/space_card_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/space_container_widget.dart';
import 'package:syncrow_web/pages/spaces_management/helper/connection_helper.dart';
import 'package:syncrow_web/pages/spaces_management/helper/space_helper.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class CommunityStructureArea extends StatefulWidget {
@ -26,6 +35,7 @@ class CommunityStructureArea extends StatefulWidget {
final ValueChanged<SpaceModel?>? onSpaceSelected;
final List<CommunityModel> communities;
final List<SpaceModel> spaces;
final List<SpaceTemplateModel>? spaceModels;
CommunityStructureArea({
this.selectedCommunity,
@ -34,6 +44,7 @@ class CommunityStructureArea extends StatefulWidget {
this.products,
required this.spaces,
this.onSpaceSelected,
this.spaceModels,
});
@override
@ -122,11 +133,14 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
communities: widget.communities,
communityName: widget.selectedCommunity?.name,
community: widget.selectedCommunity,
isSave: isSave(spaces),
isSave: SpaceHelper.isSave(spaces),
isEditingName: isEditingName,
nameController: _nameController,
onSave: _saveSpaces,
selectedSpace: widget.selectedSpace,
onDelete: _onDelete,
onDuplicate: () => {_onDuplicate(context)},
onEdit: () => {_showEditSpaceDialog()},
onEditName: () {
setState(() {
isEditingName = !isEditingName;
@ -164,14 +178,16 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
children: [
for (var connection in connections)
Opacity(
opacity: _isHighlightedConnection(connection)
opacity: ConnectionHelper.isHighlightedConnection(
connection, widget.selectedSpace)
? 1.0
: 0.3, // Adjust opacity
child: CustomPaint(
painter: CurvedLinePainter([connection])),
),
for (var entry in spaces.asMap().entries)
if (entry.value.status != SpaceStatus.deleted)
if (entry.value.status != SpaceStatus.deleted &&
entry.value.status != SpaceStatus.parentDeleted)
Positioned(
left: entry.value.position.dx,
top: entry.value.position.dy,
@ -196,15 +212,13 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
},
buildSpaceContainer: (int index) {
final bool isHighlighted =
_isHighlightedSpace(spaces[index]);
SpaceHelper.isHighlightedSpace(
spaces[index], widget.selectedSpace);
return Opacity(
opacity: isHighlighted ? 1.0 : 0.3,
child: SpaceContainerWidget(
index: index,
onDoubleTap: () {
_showEditSpaceDialog(spaces[index]);
},
onTap: () {
_selectSpace(context, spaces[index]);
},
@ -284,14 +298,20 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
builder: (BuildContext context) {
return CreateSpaceDialog(
products: widget.products,
spaceModels: widget.spaceModels,
allTags:
TagHelper.getAllTagValues(widget.communities, widget.spaceModels),
parentSpace: parentIndex != null ? spaces[parentIndex] : null,
onCreateSpace: (String name, String icon,
List<SelectedProduct> selectedProducts) {
onCreateSpace: (String name,
String icon,
List<SelectedProduct> selectedProducts,
SpaceTemplateModel? spaceModel,
List<SubspaceModel>? subspaces,
List<Tag>? tags) {
setState(() {
// Set the first space in the center or use passed position
Offset centerPosition =
position ?? _getCenterPosition(screenSize);
position ?? ConnectionHelper.getCenterPosition(screenSize);
SpaceModel newSpace = SpaceModel(
name: name,
icon: icon,
@ -299,7 +319,9 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
isPrivate: false,
children: [],
status: SpaceStatus.newSpace,
);
spaceModel: spaceModel,
subspaces: subspaces,
tags: tags);
if (parentIndex != null && direction != null) {
SpaceModel parentSpace = spaces[parentIndex];
@ -315,7 +337,6 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
parentSpace.addOutgoingConnection(newConnection);
parentSpace.children.add(newSpace);
}
spaces.add(newSpace);
_updateNodePosition(newSpace, newSpace.position);
});
@ -325,32 +346,59 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
);
}
void _showEditSpaceDialog(SpaceModel space) {
showDialog(
context: context,
builder: (BuildContext context) {
return CreateSpaceDialog(
products: widget.products,
name: space.name,
icon: space.icon,
editSpace: space,
isEdit: true,
onCreateSpace: (String name, String icon,
List<SelectedProduct> selectedProducts) {
setState(() {
// Update the space's properties
space.name = name;
space.icon = icon;
void _showEditSpaceDialog() {
if (widget.selectedSpace != null) {
showDialog(
context: context,
builder: (BuildContext context) {
return CreateSpaceDialog(
products: widget.products,
spaceModels: widget.spaceModels,
name: widget.selectedSpace!.name,
icon: widget.selectedSpace!.icon,
parentSpace: SpaceHelper.findSpaceByInternalId(
widget.selectedSpace?.parent?.internalId, spaces),
editSpace: widget.selectedSpace,
currentSpaceModel: widget.selectedSpace?.spaceModel,
tags: widget.selectedSpace?.tags,
subspaces: widget.selectedSpace?.subspaces,
isEdit: true,
allTags: TagHelper.getAllTagValues(
widget.communities, widget.spaceModels),
onCreateSpace: (String name,
String icon,
List<SelectedProduct> selectedProducts,
SpaceTemplateModel? spaceModel,
List<SubspaceModel>? subspaces,
List<Tag>? tags) {
setState(() {
// Update the space's properties
widget.selectedSpace!.name = name;
widget.selectedSpace!.icon = icon;
widget.selectedSpace!.spaceModel = spaceModel;
widget.selectedSpace!.subspaces = subspaces;
widget.selectedSpace!.tags = tags;
if (space.status != SpaceStatus.newSpace) {
space.status = SpaceStatus.modified; // Mark as modified
}
});
},
key: Key(space.name),
);
},
);
if (widget.selectedSpace!.status != SpaceStatus.newSpace) {
widget.selectedSpace!.status =
SpaceStatus.modified; // Mark as modified
}
for (var space in spaces) {
if (space.internalId == widget.selectedSpace?.internalId) {
space.status = SpaceStatus.modified;
space.subspaces = subspaces;
space.tags = tags;
space.name = name;
}
}
});
},
key: Key(widget.selectedSpace!.name),
);
},
);
}
}
void _handleHoverChanged(int index, bool isHovered) {
@ -363,10 +411,11 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
List<SpaceModel> result = [];
void flatten(SpaceModel space) {
if (space.status == SpaceStatus.deleted) return;
if (space.status == SpaceStatus.deleted ||
space.status == SpaceStatus.parentDeleted) {
return;
}
result.add(space);
for (var child in space.children) {
flatten(child);
}
@ -421,7 +470,6 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
}).toList();
if (spacesToSave.isEmpty) {
debugPrint("No new or modified spaces to save.");
return;
}
@ -434,21 +482,15 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
}
void _onDelete() {
if (widget.selectedCommunity != null &&
widget.selectedCommunity?.uuid != null &&
widget.selectedSpace == null) {
context.read<SpaceManagementBloc>().add(DeleteCommunityEvent(
communityUuid: widget.selectedCommunity!.uuid,
));
}
if (widget.selectedSpace != null) {
setState(() {
for (var space in spaces) {
if (space.uuid == widget.selectedSpace?.uuid) {
if (space.internalId == widget.selectedSpace?.internalId) {
space.status = SpaceStatus.deleted;
_markChildrenAsDeleted(space);
}
}
_removeConnectionsForDeletedSpaces();
});
}
@ -456,7 +498,8 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
void _markChildrenAsDeleted(SpaceModel parent) {
for (var child in parent.children) {
child.status = SpaceStatus.deleted;
child.status = SpaceStatus.parentDeleted;
_markChildrenAsDeleted(child);
}
}
@ -464,7 +507,9 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
void _removeConnectionsForDeletedSpaces() {
connections.removeWhere((connection) {
return connection.startSpace.status == SpaceStatus.deleted ||
connection.endSpace.status == SpaceStatus.deleted;
connection.endSpace.status == SpaceStatus.deleted ||
connection.startSpace.status == SpaceStatus.parentDeleted ||
connection.endSpace.status == SpaceStatus.parentDeleted;
});
}
@ -488,17 +533,6 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
);
}
bool _isHighlightedSpace(SpaceModel space) {
final selectedSpace = widget.selectedSpace;
if (selectedSpace == null) return true;
return space == selectedSpace ||
selectedSpace.parent?.internalId == space.internalId ||
selectedSpace.children
?.any((child) => child.internalId == space.internalId) ==
true;
}
void _deselectSpace(BuildContext context) {
context.read<SpaceManagementBloc>().add(
SelectSpaceEvent(
@ -506,25 +540,187 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
);
}
bool _isHighlightedConnection(Connection connection) {
if (widget.selectedSpace == null) return true;
void _onDuplicate(BuildContext parentContext) {
final screenWidth = MediaQuery.of(context).size.width;
return connection.startSpace == widget.selectedSpace ||
connection.endSpace == widget.selectedSpace;
if (widget.selectedSpace != null) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: ColorsManager.whiteColors,
title: Text(
"Duplicate Space",
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.headlineLarge
?.copyWith(color: ColorsManager.blackColor),
),
content: SizedBox(
width: screenWidth * 0.4,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text("Are you sure you want to duplicate?",
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineSmall),
const SizedBox(height: 15),
Text("All the child spaces will be duplicated.",
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: ColorsManager.lightGrayColor)),
const SizedBox(width: 15),
],
),
),
actions: [
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
SizedBox(
width: 200,
child: CancelButton(
onPressed: () {
Navigator.of(context).pop();
},
label: "Cancel",
),
),
const SizedBox(width: 10),
SizedBox(
width: 200,
child: DefaultButton(
onPressed: () {
Navigator.of(context).pop();
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return DuplicateProcessDialog(
onDuplicate: () {
_duplicateSpace(widget.selectedSpace!);
_deselectSpace(parentContext);
},
);
},
);
},
backgroundColor: ColorsManager.secondaryColor,
borderRadius: 10,
foregroundColor: ColorsManager.whiteColors,
child: const Text('OK'),
),
),
])
],
);
},
);
}
}
Offset _getCenterPosition(Size screenSize) {
return Offset(
screenSize.width / 2 - 260,
screenSize.height / 2 - 200,
);
}
void _duplicateSpace(SpaceModel space) {
final Map<SpaceModel, SpaceModel> originalToDuplicate = {};
const double horizontalGap = 200.0;
const double verticalGap = 100.0;
bool isSave(List<SpaceModel> spaces) {
return spaces.isNotEmpty &&
spaces.any((space) =>
space.status == SpaceStatus.newSpace ||
space.status == SpaceStatus.modified ||
space.status == SpaceStatus.deleted);
SpaceModel duplicateRecursive(SpaceModel original, Offset parentPosition,
SpaceModel? duplicatedParent) {
Offset newPosition =
Offset(parentPosition.dx + horizontalGap, original.position.dy);
while (spaces.any((s) =>
(s.position - newPosition).distance < horizontalGap &&
s.status != SpaceStatus.deleted)) {
newPosition += Offset(horizontalGap, 0);
}
final duplicatedName =
SpaceHelper.generateUniqueSpaceName(original.name, spaces);
final duplicated = SpaceModel(
name: duplicatedName,
icon: original.icon,
position: newPosition,
isPrivate: original.isPrivate,
children: [],
status: SpaceStatus.newSpace,
parent: duplicatedParent,
spaceModel: original.spaceModel,
subspaces: original.subspaces,
tags: original.tags,
);
originalToDuplicate[original] = duplicated;
setState(() {
spaces.add(duplicated);
_updateNodePosition(duplicated, duplicated.position);
if (duplicatedParent != null) {
final newConnection = Connection(
startSpace: duplicatedParent,
endSpace: duplicated,
direction: original.incomingConnection?.direction ?? 'down',
);
connections.add(newConnection);
duplicated.incomingConnection = newConnection;
duplicatedParent.addOutgoingConnection(newConnection);
}
if (original.parent != null && duplicatedParent == null) {
final originalParent = original.parent!;
final duplicatedParent =
originalToDuplicate[originalParent] ?? originalParent;
final parentConnection = Connection(
startSpace: duplicatedParent,
endSpace: duplicated,
direction: original.incomingConnection?.direction ?? "down",
);
connections.add(parentConnection);
duplicated.incomingConnection = parentConnection;
duplicatedParent.addOutgoingConnection(parentConnection);
}
});
final childrenWithDownDirection = original.children
.where((child) =>
child.incomingConnection?.direction == "down" &&
child.status != SpaceStatus.deleted)
.toList();
Offset childStartPosition = childrenWithDownDirection.length == 1
? duplicated.position
: newPosition + Offset(0, verticalGap);
for (final child in original.children) {
final isDownDirection =
child.incomingConnection?.direction == "down" ?? false;
if (isDownDirection && childrenWithDownDirection.length == 1) {
childStartPosition = duplicated.position + Offset(0, verticalGap);
} else if (!isDownDirection) {
childStartPosition = duplicated.position + Offset(horizontalGap, 0);
}
final duplicatedChild =
duplicateRecursive(child, childStartPosition, duplicated);
duplicated.children.add(duplicatedChild);
childStartPosition += Offset(0, verticalGap);
}
return duplicated;
}
if (space.parent == null) {
duplicateRecursive(space, space.position, null);
} else {
final duplicatedParent =
originalToDuplicate[space.parent!] ?? space.parent!;
duplicateRecursive(space, space.position, duplicatedParent);
}
}
}

View File

@ -4,12 +4,14 @@ import 'package:syncrow_web/utils/color_manager.dart';
class CounterWidget extends StatefulWidget {
final int initialCount;
final ValueChanged<int> onCountChanged;
final bool isCreate;
const CounterWidget({
Key? key,
this.initialCount = 0,
required this.onCountChanged,
}) : super(key: key);
const CounterWidget(
{Key? key,
this.initialCount = 0,
required this.onCountChanged,
required this.isCreate})
: super(key: key);
@override
State<CounterWidget> createState() => _CounterWidgetState();
@ -53,25 +55,26 @@ class _CounterWidgetState extends State<CounterWidget> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_buildCounterButton(Icons.remove, _decrementCounter),
_buildCounterButton(Icons.remove, _decrementCounter,!widget.isCreate ),
const SizedBox(width: 8),
Text(
'$_counter',
style: theme.textTheme.bodyLarge?.copyWith(color: ColorsManager.spaceColor),
style: theme.textTheme.bodyLarge
?.copyWith(color: ColorsManager.spaceColor),
),
const SizedBox(width: 8),
_buildCounterButton(Icons.add, _incrementCounter),
_buildCounterButton(Icons.add, _incrementCounter, false),
],
),
);
}
Widget _buildCounterButton(IconData icon, VoidCallback onPressed) {
Widget _buildCounterButton(IconData icon, VoidCallback onPressed, bool isDisabled) {
return GestureDetector(
onTap: onPressed,
onTap: isDisabled? null: onPressed,
child: Icon(
icon,
color: ColorsManager.spaceColor,
color: isDisabled? ColorsManager.spaceColor.withOpacity(0.3): ColorsManager.spaceColor,
size: 18,
),
);

View File

@ -1,20 +1,34 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/common/edit_chip.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/views/add_device_type_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/add_device_type_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/dialogs/icon_selection_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/hoverable_button.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/views/assign_tag_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/views/create_subspace_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/view/link_space_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/space_icon_const.dart';
class CreateSpaceDialog extends StatefulWidget {
final Function(String, String, List<SelectedProduct> selectedProducts)
onCreateSpace;
final Function(
String,
String,
List<SelectedProduct> selectedProducts,
SpaceTemplateModel? spaceModel,
List<SubspaceModel>? subspaces,
List<Tag>? tags) onCreateSpace;
final List<ProductModel>? products;
final String? name;
final String? icon;
@ -22,6 +36,11 @@ class CreateSpaceDialog extends StatefulWidget {
final List<SelectedProduct> selectedProducts;
final SpaceModel? parentSpace;
final SpaceModel? editSpace;
final List<SpaceTemplateModel>? spaceModels;
final List<SubspaceModel>? subspaces;
final List<Tag>? tags;
final List<String>? allTags;
final SpaceTemplateModel? currentSpaceModel;
const CreateSpaceDialog(
{super.key,
@ -32,7 +51,12 @@ class CreateSpaceDialog extends StatefulWidget {
this.icon,
this.isEdit = false,
this.editSpace,
this.selectedProducts = const []});
this.allTags,
this.selectedProducts = const [],
this.spaceModels,
this.subspaces,
this.tags,
this.currentSpaceModel});
@override
CreateSpaceDialogState createState() => CreateSpaceDialogState();
@ -40,12 +64,15 @@ class CreateSpaceDialog extends StatefulWidget {
class CreateSpaceDialogState extends State<CreateSpaceDialog> {
String selectedIcon = Assets.location;
SpaceTemplateModel? selectedSpaceModel;
String enteredName = '';
List<SelectedProduct> selectedProducts = [];
late TextEditingController nameController;
bool isOkButtonEnabled = false;
bool isNameFieldInvalid = false;
bool isNameFieldExist = false;
List<SubspaceModel>? subspaces;
List<Tag>? tags;
@override
void initState() {
@ -56,198 +83,431 @@ class CreateSpaceDialogState extends State<CreateSpaceDialog> {
widget.selectedProducts.isNotEmpty ? widget.selectedProducts : [];
isOkButtonEnabled =
enteredName.isNotEmpty || nameController.text.isNotEmpty;
if (widget.currentSpaceModel != null) {
subspaces = [];
tags = [];
} else {
tags = widget.tags ?? [];
subspaces = widget.subspaces ?? [];
}
selectedSpaceModel = widget.currentSpaceModel;
}
@override
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return AlertDialog(
title: widget.isEdit
? const Text('Edit Space')
: const Text('Create New Space'),
backgroundColor: ColorsManager.whiteColors,
content: SizedBox(
width: screenWidth * 0.5, // Limit dialog width
width: screenWidth * 0.5,
child: SingleChildScrollView(
// Scrollable content to prevent overflow
child: Column(
mainAxisSize: MainAxisSize.min,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(
alignment: Alignment.center,
children: [
Container(
width: screenWidth * 0.1, // Adjusted width
height: screenWidth * 0.1, // Adjusted height
decoration: const BoxDecoration(
color: ColorsManager.boxColor,
shape: BoxShape.circle,
),
),
SvgPicture.asset(
selectedIcon,
width: screenWidth * 0.04,
height: screenWidth * 0.04,
),
Positioned(
top: 6,
right: 6,
child: InkWell(
onTap: _showIconSelectionDialog,
child: Container(
width: screenWidth * 0.020,
height: screenWidth * 0.020,
decoration: const BoxDecoration(
color: ColorsManager.whiteColors,
shape: BoxShape.circle,
),
child: SvgPicture.asset(
Assets.iconEdit,
width: screenWidth * 0.06,
height: screenWidth * 0.06,
),
),
),
),
],
),
const SizedBox(width: 16),
Expanded(
// Ensure the text field expands responsively
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
Expanded(
flex: 1,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
// crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 50),
Stack(
alignment: Alignment.center,
children: [
TextField(
controller: nameController,
onChanged: (value) {
enteredName = value.trim();
setState(() {
isNameFieldExist = false;
isOkButtonEnabled = false;
isNameFieldInvalid = value.isEmpty;
if (!isNameFieldInvalid) {
if (_isNameConflict(value)) {
isNameFieldExist = true;
isOkButtonEnabled = false;
} else {
isNameFieldExist = false;
isOkButtonEnabled = true;
}
}
});
},
style: const TextStyle(color: ColorsManager.blackColor),
decoration: InputDecoration(
hintText: 'Please enter the name',
hintStyle: const TextStyle(
fontSize: 14,
color: ColorsManager.lightGrayColor,
fontWeight: FontWeight.w400,
),
filled: true,
fillColor: ColorsManager.boxColor,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: isNameFieldInvalid || isNameFieldExist
? ColorsManager.red
: ColorsManager.boxColor,
width: 1.5,
Container(
width: screenWidth * 0.1,
height: screenWidth * 0.1,
decoration: const BoxDecoration(
color: ColorsManager.boxColor,
shape: BoxShape.circle,
),
),
SvgPicture.asset(
selectedIcon,
width: screenWidth * 0.04,
height: screenWidth * 0.04,
),
Positioned(
top: 20,
right: 20,
child: InkWell(
onTap: _showIconSelectionDialog,
child: Container(
width: 24,
height: 24,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(
color: ColorsManager.boxColor,
width: 1.5,
child: SvgPicture.asset(
Assets.iconEdit,
width: 16,
height: 16,
),
),
),
),
if (isNameFieldInvalid)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'*Space name should not be empty.',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.red),
),
),
if (isNameFieldExist)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'*Name already exist',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.red),
),
),
const SizedBox(height: 16),
if (selectedProducts.isNotEmpty)
_buildSelectedProductsButtons(widget.products ?? [])
else
DefaultButton(
onPressed: () {
showDialog(
context: context,
builder: (context) => AddDeviceWidget(
products: widget.products,
onProductsSelected: (selectedProductsMap) {
setState(() {
selectedProducts = selectedProductsMap;
});
},
),
);
},
backgroundColor: ColorsManager.textFieldGreyColor,
foregroundColor: ColorsManager.blackColor,
borderColor: ColorsManager.neutralGray,
borderRadius: 16.0,
padding: 10.0, // Reduced padding for smaller size
child: Align(
alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.only(left: 6.0),
child: SvgPicture.asset(
Assets.addIcon,
width: screenWidth *
0.015, // Adjust icon size
height: screenWidth * 0.015,
),
),
const SizedBox(width: 3),
Flexible(
child: Text(
'Add devices / Assign a space model',
overflow: TextOverflow
.ellipsis, // Prevent overflow
style: Theme.of(context)
.textTheme
.bodyMedium,
),
),
],
),
)),
],
),
),
],
],
),
),
const SizedBox(width: 20),
Expanded(
flex: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: screenWidth * 0.25,
child: TextField(
controller: nameController,
onChanged: (value) {
enteredName = value.trim();
setState(() {
isNameFieldExist = false;
isOkButtonEnabled = false;
isNameFieldInvalid = value.isEmpty;
if (!isNameFieldInvalid) {
if (_isNameConflict(value)) {
isNameFieldExist = true;
isOkButtonEnabled = false;
} else {
isNameFieldExist = false;
isOkButtonEnabled = true;
}
}
});
},
style: Theme.of(context).textTheme.bodyMedium,
decoration: InputDecoration(
hintText: 'Please enter the name',
hintStyle: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: ColorsManager.lightGrayColor),
filled: true,
fillColor: ColorsManager.boxColor,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: isNameFieldInvalid || isNameFieldExist
? ColorsManager.red
: ColorsManager.boxColor,
width: 1.5,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(
color: ColorsManager.boxColor,
width: 1.5,
),
),
),
),
),
if (isNameFieldInvalid)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'*Space name should not be empty.',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.red),
),
),
if (isNameFieldExist)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
'*Name already exist',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.red),
),
),
const SizedBox(height: 10),
selectedSpaceModel == null
? TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
),
onPressed: () {
_showLinkSpaceModelDialog(context);
},
child: const ButtonContentWidget(
svgAssets: Assets.link,
label: 'Link a space model',
),
)
: Container(
width: screenWidth * 0.25,
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 16.0),
decoration: BoxDecoration(
color: ColorsManager.boxColor,
borderRadius: BorderRadius.circular(10),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
Chip(
label: Text(
selectedSpaceModel?.modelName ?? '',
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(
color: ColorsManager.spaceColor),
),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(
color: ColorsManager.transparentColor,
width: 0,
),
),
deleteIcon: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager.lightGrayColor,
width: 1.5,
),
),
child: const Icon(
Icons.close,
size: 16,
color: ColorsManager.lightGrayColor,
),
),
onDeleted: () => setState(() {
this.selectedSpaceModel = null;
})),
],
),
),
const SizedBox(height: 25),
Row(
children: [
const Expanded(
child: Divider(
color: ColorsManager.neutralGray,
thickness: 1.0,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6.0),
child: Text(
'OR',
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(fontWeight: FontWeight.bold),
),
),
const Expanded(
child: Divider(
color: ColorsManager.neutralGray,
thickness: 1.0,
),
),
],
),
const SizedBox(height: 25),
subspaces == null || subspaces!.isEmpty
? TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
overlayColor: ColorsManager.transparentColor,
),
onPressed: () async {
_showSubSpaceDialog(context, enteredName, [],
false, widget.products, subspaces);
},
child: const ButtonContentWidget(
icon: Icons.add,
label: 'Create Sub Space',
),
)
: SizedBox(
width: screenWidth * 0.25,
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: ColorsManager.textFieldGreyColor,
width: 3.0, // Border width
),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
if (subspaces != null)
...subspaces!.map((subspace) {
return Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
SubspaceNameDisplayWidget(
text: subspace.subspaceName,
validateName: (updatedName) {
bool nameExists =
subspaces!.any((s) {
bool isSameId = s.internalId ==
subspace.internalId;
bool isSameName = s.subspaceName
.trim()
.toLowerCase() ==
updatedName
.trim()
.toLowerCase();
return !isSameId && isSameName;
});
return !nameExists;
},
onNameChanged: (updatedName) {
setState(() {
subspace.subspaceName =
updatedName;
});
},
),
],
);
}),
EditChip(
onTap: () async {
_showSubSpaceDialog(context, enteredName,
[], true, widget.products, subspaces);
},
)
],
),
),
),
const SizedBox(height: 10),
(tags?.isNotEmpty == true ||
subspaces?.any((subspace) =>
subspace.tags?.isNotEmpty == true) ==
true)
? SizedBox(
width: screenWidth * 0.25,
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: ColorsManager.textFieldGreyColor,
width: 3.0, // Border width
),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
// Combine tags from spaceModel and subspaces
...TagHelper.groupTags([
...?tags,
...?subspaces?.expand(
(subspace) => subspace.tags ?? [])
]).entries.map(
(entry) => Chip(
avatar: SizedBox(
width: 24,
height: 24,
child: SvgPicture.asset(
entry.key.icon ??
'assets/icons/gateway.svg',
fit: BoxFit.contain,
),
),
label: Text(
'x${entry.value}', // Show count
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager
.spaceColor),
),
backgroundColor:
ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(16),
side: const BorderSide(
color: ColorsManager.spaceColor,
),
),
),
),
EditChip(onTap: () async {
final result = await showDialog(
context: context,
builder: (context) => AssignTagDialog(
products: widget.products,
subspaces: subspaces,
allTags: widget.allTags,
addedProducts: TagHelper
.createInitialSelectedProductsForTags(
tags ?? [], subspaces),
title: 'Edit Device',
initialTags:
TagHelper.generateInitialForTags(
spaceTags: tags,
subspaces: subspaces),
spaceName: widget.name ?? '',
onSave:
(updatedTags, updatedSubspaces) {
setState(() {
tags = updatedTags;
subspaces = updatedSubspaces;
});
},
),
);
})
],
),
),
)
: TextButton(
onPressed: () {
_showTagCreateDialog(
context,
enteredName,
widget.isEdit,
widget.products,
);
},
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
),
child: const ButtonContentWidget(
icon: Icons.add,
label: 'Add Devices',
))
],
),
),
],
),
@ -278,7 +538,12 @@ class CreateSpaceDialogState extends State<CreateSpaceDialog> {
: (widget.name ?? '');
if (newName.isNotEmpty) {
widget.onCreateSpace(
newName, selectedIcon, selectedProducts);
newName,
selectedIcon,
selectedProducts,
selectedSpaceModel,
subspaces,
tags);
Navigator.of(context).pop();
}
}
@ -313,97 +578,162 @@ class CreateSpaceDialogState extends State<CreateSpaceDialog> {
);
}
Widget _buildSelectedProductsButtons(List<ProductModel> products) {
final screenWidth = MediaQuery.of(context).size.width;
bool _isNameConflict(String value) {
final parentSpace = widget.parentSpace;
final editSpace = widget.editSpace;
final siblings = parentSpace?.children
.where((child) => child.uuid != editSpace?.uuid)
.toList() ??
[];
final siblingConflict = siblings.any((child) => child.name == value);
final parentConflict =
parentSpace?.name == value && parentSpace?.uuid != editSpace?.uuid;
final parentOfEditSpaceConflict = editSpace?.parent?.name == value &&
editSpace?.parent?.uuid != editSpace?.uuid;
final childConflict =
editSpace?.children.any((child) => child.name == value) ?? false;
return siblingConflict ||
parentConflict ||
parentOfEditSpaceConflict ||
childConflict;
}
return Container(
width: screenWidth * 0.6,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: ColorsManager.neutralGray,
width: 2,
),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (var i = 0; i < selectedProducts.length; i++) ...[
HoverableButton(
iconPath:
_mapIconToProduct(selectedProducts[i].productId, products),
text: 'x${selectedProducts[i].count}',
onTap: () {
void _showLinkSpaceModelDialog(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return LinkSpaceModelDialog(
spaceModels: widget.spaceModels ?? [],
onSave: (selectedModel) {
if (selectedModel != null) {
setState(() {
selectedSpaceModel = selectedModel;
subspaces = null;
tags = null;
});
}
},
);
},
);
}
void _showSubSpaceDialog(
BuildContext context,
String name,
final List<Tag>? spaceTags,
bool isEdit,
List<ProductModel>? products,
final List<SubspaceModel>? existingSubSpaces) {
showDialog(
context: context,
builder: (BuildContext context) {
return CreateSubSpaceDialog(
spaceName: name,
dialogTitle: isEdit ? 'Edit Sub-space' : 'Create Sub-space',
spaceTags: spaceTags,
isEdit: isEdit,
products: products,
existingSubSpaces: existingSubSpaces,
onSave: (slectedSubspaces) {
final List<Tag> tagsToAppendToSpace = [];
if (slectedSubspaces != null) {
final updatedIds =
slectedSubspaces.map((s) => s.internalId).toSet();
if (existingSubSpaces != null) {
final deletedSubspaces = existingSubSpaces
.where((s) => !updatedIds.contains(s.internalId))
.toList();
for (var s in deletedSubspaces) {
if (s.tags != null) {
tagsToAppendToSpace.addAll(s.tags!);
}
}
}
}
if (slectedSubspaces != null) {
setState(() {
selectedProducts.remove(selectedProducts[i]);
subspaces = slectedSubspaces;
tags?.addAll(tagsToAppendToSpace);
selectedSpaceModel = null;
});
// Handle button tap
},
),
if (i < selectedProducts.length - 1)
const SizedBox(
width: 2), // Add space except after the last button
],
const SizedBox(width: 2),
GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) => AddDeviceWidget(
products: widget.products,
initialSelectedProducts: selectedProducts,
onProductsSelected: (selectedProductsMap) {
setState(() {
selectedProducts = selectedProductsMap;
});
},
),
}
});
},
);
}
void _showTagCreateDialog(BuildContext context, String name, bool isEdit,
List<ProductModel>? products) {
isEdit
? showDialog(
context: context,
builder: (BuildContext context) {
return AssignTagDialog(
title: 'Edit Device',
addedProducts: TagHelper.createInitialSelectedProductsForTags(
tags, subspaces),
spaceName: name,
products: products,
subspaces: subspaces,
allTags: widget.allTags,
onSave: (selectedSpaceTags, selectedSubspaces) {
setState(() {
tags = selectedSpaceTags;
selectedSpaceModel = null;
if (selectedSubspaces != null) {
if (subspaces != null) {
for (final subspace in subspaces!) {
for (final selectedSubspace in selectedSubspaces) {
if (subspace.subspaceName ==
selectedSubspace.subspaceName) {
subspace.tags = selectedSubspace.tags;
}
}
}
}
}
});
},
);
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: ColorsManager.whiteColors,
borderRadius: BorderRadius.circular(16),
),
child: const Icon(
Icons.add,
color: ColorsManager.spaceColor,
size: 24,
),
),
),
],
),
);
}
)
: showDialog(
context: context,
builder: (BuildContext context) {
return AddDeviceTypeWidget(
spaceName: name,
products: products,
subspaces: subspaces,
spaceTags: tags,
isCreate: true,
allTags: widget.allTags,
initialSelectedProducts:
TagHelper.createInitialSelectedProductsForTags(
tags, subspaces),
onSave: (selectedSpaceTags, selectedSubspaces) {
setState(() {
tags = selectedSpaceTags;
selectedSpaceModel = null;
bool _isNameConflict(String value) {
return (widget.parentSpace?.children.any((child) => child.name == value) ??
false) ||
(widget.parentSpace?.name == value) ||
(widget.editSpace?.parent?.name == value) ||
(widget.editSpace?.children.any((child) => child.name == value) ??
false);
}
String _mapIconToProduct(String uuid, List<ProductModel> products) {
// Find the product with the matching UUID
final product = products.firstWhere(
(product) => product.uuid == uuid,
orElse: () => ProductModel(
uuid: '',
catName: '',
prodId: '',
prodType: '',
name: '',
icon: Assets.presenceSensor,
),
);
return product.icon ?? Assets.presenceSensor;
if (selectedSubspaces != null) {
if (subspaces != null) {
for (final subspace in subspaces!) {
for (final selectedSubspace in selectedSubspaces) {
if (subspace.subspaceName ==
selectedSubspace.subspaceName) {
subspace.tags = selectedSubspace.tags;
}
}
}
}
}
});
},
);
},
);
}
}

View File

@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class DuplicateProcessDialog extends StatefulWidget {
final VoidCallback onDuplicate;
const DuplicateProcessDialog({required this.onDuplicate, Key? key})
: super(key: key);
@override
_DuplicateProcessDialogState createState() => _DuplicateProcessDialogState();
}
class _DuplicateProcessDialogState extends State<DuplicateProcessDialog> {
bool isDuplicating = true;
@override
void initState() {
super.initState();
_startDuplication();
}
void _startDuplication() async {
WidgetsBinding.instance.addPostFrameCallback((_) {
widget.onDuplicate();
});
await Future.delayed(const Duration(seconds: 2));
setState(() {
isDuplicating = false;
});
await Future.delayed(const Duration(seconds: 2));
if (mounted) {
Navigator.of(context).pop();
}
}
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return AlertDialog(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
content: SizedBox(
width: screenWidth * 0.4,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (isDuplicating) ...[
const CircularProgressIndicator(
color: ColorsManager.vividBlue,
),
const SizedBox(height: 15),
Text(
"Duplicating in progress",
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(color: ColorsManager.primaryColor),
textAlign: TextAlign.center,
),
] else ...[
const Icon(
Icons.check_circle,
color: ColorsManager.vividBlue,
size: 50,
),
const SizedBox(height: 15),
Text(
"Duplicating successful",
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(color: ColorsManager.primaryColor),
),
],
],
),
),
);
}
}

View File

@ -17,6 +17,7 @@ class LoadedSpaceView extends StatefulWidget {
final SpaceModel? selectedSpace;
final List<ProductModel>? products;
final List<SpaceTemplateModel>? spaceModels;
final bool shouldNavigateToSpaceModelPage;
const LoadedSpaceView({
super.key,
@ -25,18 +26,42 @@ class LoadedSpaceView extends StatefulWidget {
this.selectedSpace,
this.products,
this.spaceModels,
required this.shouldNavigateToSpaceModelPage,
});
@override
_LoadedStateViewState createState() => _LoadedStateViewState();
_LoadedSpaceViewState createState() => _LoadedSpaceViewState();
}
class _LoadedStateViewState extends State<LoadedSpaceView> {
class _LoadedSpaceViewState extends State<LoadedSpaceView> {
late List<SpaceTemplateModel> _spaceModels;
@override
void initState() {
super.initState();
_spaceModels = List.from(widget.spaceModels ?? []);
}
@override
void didUpdateWidget(covariant LoadedSpaceView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.spaceModels != oldWidget.spaceModels) {
setState(() {
_spaceModels = List.from(widget.spaceModels ?? []);
});
}
}
void _onSpaceModelsUpdated(List<SpaceTemplateModel> updatedModels) {
if (mounted && updatedModels != _spaceModels) {
setState(() {
_spaceModels = updatedModels;
});
}
}
@override
Widget build(BuildContext context) {
final bool hasSpaceModels =
widget.spaceModels != null && widget.spaceModels!.isNotEmpty;
return Stack(
clipBehavior: Clip.none,
children: [
@ -48,15 +73,16 @@ class _LoadedStateViewState extends State<LoadedSpaceView> {
widget.selectedCommunity?.uuid ??
'',
),
hasSpaceModels
widget.shouldNavigateToSpaceModelPage
? Expanded(
child: BlocProvider(
create: (context) => SpaceModelBloc(
api: SpaceModelManagementApi(),
initialSpaceModels: widget.spaceModels ?? [],
initialSpaceModels: _spaceModels,
),
child: SpaceModelPage(
products: widget.products,
onSpaceModelsUpdated: _onSpaceModelsUpdated,
),
),
)
@ -66,6 +92,7 @@ class _LoadedStateViewState extends State<LoadedSpaceView> {
spaces: widget.selectedCommunity?.spaces ?? [],
products: widget.products,
communities: widget.communities,
spaceModels: _spaceModels,
),
],
),
@ -73,13 +100,4 @@ class _LoadedStateViewState extends State<LoadedSpaceView> {
],
);
}
SpaceModel? findSpaceByUuid(String? uuid, List<CommunityModel> communities) {
for (var community in communities) {
for (var space in community.spaces) {
if (space.uuid == uuid) return space;
}
}
return null;
}
}

View File

@ -0,0 +1,118 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/add_device_type_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/widgets/hoverable_button.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
class SelectedProductsButtons extends StatelessWidget {
final List<ProductModel> products;
final List<SelectedProduct> selectedProducts;
final Function(List<SelectedProduct>) onProductsUpdated;
final BuildContext context;
const SelectedProductsButtons({
Key? key,
required this.products,
required this.selectedProducts,
required this.onProductsUpdated,
required this.context,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return Container(
width: screenWidth * 0.6,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: ColorsManager.neutralGray,
width: 2,
),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
..._buildSelectedProductButtons(),
_buildAddButton(),
],
),
);
}
List<Widget> _buildSelectedProductButtons() {
return [
for (var i = 0; i < selectedProducts.length; i++) ...[
HoverableButton(
iconPath: _mapIconToProduct(selectedProducts[i].productId, products),
text: 'x${selectedProducts[i].count}',
onTap: () {
_removeProduct(i);
},
),
if (i < selectedProducts.length - 1)
const SizedBox(width: 2), // Add space except after the last button
],
];
}
Widget _buildAddButton() {
return GestureDetector(
onTap: _showAddDeviceDialog,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: ColorsManager.whiteColors,
borderRadius: BorderRadius.circular(16),
),
child: const Icon(
Icons.add,
color: ColorsManager.spaceColor,
size: 24,
),
),
);
}
void _showAddDeviceDialog() {
showDialog(
context: context,
builder: (context) => AddDeviceWidget(
products: products,
initialSelectedProducts: selectedProducts,
onProductsSelected: (selectedProductsMap) {
onProductsUpdated(selectedProductsMap);
},
),
);
}
void _removeProduct(int index) {
final updatedProducts = [...selectedProducts];
updatedProducts.removeAt(index);
onProductsUpdated(updatedProducts);
}
String _mapIconToProduct(String uuid, List<ProductModel> products) {
// Find the product with the matching UUID
final product = products.firstWhere(
(product) => product.uuid == uuid,
orElse: () => ProductModel(
uuid: '',
catName: '',
prodId: '',
prodType: '',
name: '',
icon: Assets.presenceSensor,
),
);
return product.icon ?? Assets.presenceSensor;
}
}

View File

@ -199,9 +199,11 @@ class _SidebarWidgetState extends State<SidebarWidget> {
},
children: hasChildren
? community.spaces
.where((space) => (space.status != SpaceStatus.deleted ||
space.status != SpaceStatus.parentDeleted))
.map((space) => _buildSpaceTile(space, community))
.toList()
: null, // Render spaces within the community
: null,
);
}

View File

@ -20,8 +20,7 @@ class SpaceWidget extends StatelessWidget {
top: position.dy,
child: GestureDetector(
onTap: onTap,
child:
Container(
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: ColorsManager.whiteColors,
@ -39,11 +38,10 @@ class SpaceWidget extends StatelessWidget {
children: [
const Icon(Icons.location_on, color: ColorsManager.spaceColor),
const SizedBox(width: 8),
Text(name, style: const TextStyle(fontSize: 16)),
Text(name, style: Theme.of(context).textTheme.bodyMedium),
],
),
),
),
);
}

View File

@ -0,0 +1,152 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart';
class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
AssignTagBloc() : super(AssignTagInitial()) {
on<InitializeTags>((event, emit) {
final initialTags = event.initialTags ?? [];
final existingTagCounts = <String, int>{};
for (var tag in initialTags) {
if (tag.product != null) {
existingTagCounts[tag.product!.uuid] =
(existingTagCounts[tag.product!.uuid] ?? 0) + 1;
}
}
final allTags = <Tag>[];
for (var selectedProduct in event.addedProducts) {
final existingCount = existingTagCounts[selectedProduct.productId] ?? 0;
if (selectedProduct.count == 0 ||
selectedProduct.count <= existingCount) {
allTags.addAll(initialTags
.where((tag) => tag.product?.uuid == selectedProduct.productId));
continue;
}
final missingCount = selectedProduct.count - existingCount;
allTags.addAll(initialTags
.where((tag) => tag.product?.uuid == selectedProduct.productId));
if (missingCount > 0) {
allTags.addAll(List.generate(
missingCount,
(index) => Tag(
tag: '',
product: selectedProduct.product,
location: 'Main Space',
),
));
}
}
emit(AssignTagLoaded(
tags: allTags,
isSaveEnabled: _validateTags(allTags),
errorMessage: ''));
});
on<UpdateTagEvent>((event, emit) {
final currentState = state;
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final tags = List<Tag>.from(currentState.tags);
tags[event.index].tag = event.tag;
emit(AssignTagLoaded(
tags: tags,
isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags),
));
}
});
on<UpdateLocation>((event, emit) {
final currentState = state;
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final tags = List<Tag>.from(currentState.tags);
// Use copyWith for immutability
tags[event.index] =
tags[event.index].copyWith(location: event.location);
emit(AssignTagLoaded(
tags: tags,
isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags),
));
}
});
on<ValidateTags>((event, emit) {
final currentState = state;
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final tags = List<Tag>.from(currentState.tags);
emit(AssignTagLoaded(
tags: tags,
isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags),
));
}
});
on<DeleteTag>((event, emit) {
final currentState = state;
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final updatedTags = List<Tag>.from(currentState.tags)
..remove(event.tagToDelete);
emit(AssignTagLoaded(
tags: updatedTags,
isSaveEnabled: _validateTags(updatedTags),
errorMessage: _getValidationError(updatedTags),
));
} else {
emit(const AssignTagLoaded(
tags: [],
isSaveEnabled: false,
errorMessage: 'Failed to delete tag'));
}
});
}
bool _validateTags(List<Tag> tags) {
final uniqueTags = tags.map((tag) => tag.tag?.trim() ?? '').toSet();
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
final isValid = uniqueTags.length == tags.length && !hasEmptyTag;
return isValid;
}
String? _getValidationError(List<Tag> tags) {
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
if (hasEmptyTag) {
return 'Tags cannot be empty.';
}
final duplicateTags = tags
.map((tag) => tag.tag?.trim() ?? '')
.fold<Map<String, int>>({}, (map, tag) {
map[tag] = (map[tag] ?? 0) + 1;
return map;
})
.entries
.where((entry) => entry.value > 1)
.map((entry) => entry.key)
.toList();
if (duplicateTags.isNotEmpty) {
return 'Duplicate tags found: ${duplicateTags.join(', ')}';
}
return null;
}
}

View File

@ -0,0 +1,55 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
abstract class AssignTagEvent extends Equatable {
const AssignTagEvent();
@override
List<Object> get props => [];
}
class InitializeTags extends AssignTagEvent {
final List<Tag>? initialTags;
final List<SelectedProduct> addedProducts;
const InitializeTags({
required this.initialTags,
required this.addedProducts,
});
@override
List<Object> get props => [initialTags ?? [], addedProducts];
}
class UpdateTagEvent extends AssignTagEvent {
final int index;
final String tag;
const UpdateTagEvent({required this.index, required this.tag});
@override
List<Object> get props => [index, tag];
}
class UpdateLocation extends AssignTagEvent {
final int index;
final String location;
const UpdateLocation({required this.index, required this.location});
@override
List<Object> get props => [index, location];
}
class ValidateTags extends AssignTagEvent {}
class DeleteTag extends AssignTagEvent {
final Tag tagToDelete;
final List<Tag> tags;
const DeleteTag({required this.tagToDelete, required this.tags});
@override
List<Object> get props => [tagToDelete, tags];
}

View File

@ -0,0 +1,38 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
abstract class AssignTagState extends Equatable {
const AssignTagState();
@override
List<Object> get props => [];
}
class AssignTagInitial extends AssignTagState {}
class AssignTagLoading extends AssignTagState {}
class AssignTagLoaded extends AssignTagState {
final List<Tag> tags;
final bool isSaveEnabled;
final String? errorMessage;
const AssignTagLoaded({
required this.tags,
required this.isSaveEnabled,
required this.errorMessage,
});
@override
List<Object> get props => [tags, isSaveEnabled, errorMessage ?? ''];
}
class AssignTagError extends AssignTagState {
final String errorMessage;
const AssignTagError(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}

View File

@ -0,0 +1,315 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/dialog_dropdown.dart';
import 'package:syncrow_web/common/dialog_textfield_dropdown.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/add_device_type/views/add_device_type_widget.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_event.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class AssignTagDialog extends StatelessWidget {
final List<ProductModel>? products;
final List<SubspaceModel>? subspaces;
final List<Tag>? initialTags;
final ValueChanged<List<Tag>>? onTagsAssigned;
final List<SelectedProduct> addedProducts;
final List<String>? allTags;
final String spaceName;
final String title;
final Function(List<Tag>, List<SubspaceModel>?)? onSave;
const AssignTagDialog(
{Key? key,
required this.products,
required this.subspaces,
required this.addedProducts,
this.initialTags,
this.onTagsAssigned,
this.allTags,
required this.spaceName,
required this.title,
this.onSave})
: super(key: key);
@override
Widget build(BuildContext context) {
final List<String> locations = (subspaces ?? [])
.map((subspace) => subspace.subspaceName)
.toList()
..add('Main Space');
return BlocProvider(
create: (_) => AssignTagBloc()
..add(InitializeTags(
initialTags: initialTags,
addedProducts: addedProducts,
)),
child: BlocBuilder<AssignTagBloc, AssignTagState>(
builder: (context, state) {
if (state is AssignTagLoaded) {
final controllers = List.generate(
state.tags.length,
(index) => TextEditingController(text: state.tags[index].tag),
);
return AlertDialog(
title: Text(title),
backgroundColor: ColorsManager.whiteColors,
content: SingleChildScrollView(
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(20),
child: DataTable(
headingRowColor: WidgetStateProperty.all(
ColorsManager.dataHeaderGrey),
border: TableBorder.all(
color: ColorsManager.dataHeaderGrey,
width: 1,
borderRadius: BorderRadius.circular(20),
),
columns: [
DataColumn(
label: Text('#',
style:
Theme.of(context).textTheme.bodyMedium)),
DataColumn(
label: Text('Device',
style:
Theme.of(context).textTheme.bodyMedium)),
DataColumn(
numeric: false,
label: Text('Tag',
style:
Theme.of(context).textTheme.bodyMedium)),
DataColumn(
label: Text('Location',
style:
Theme.of(context).textTheme.bodyMedium)),
],
rows: state.tags.isEmpty
? [
DataRow(cells: [
DataCell(
Center(
child: Text('No Data Available',
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: ColorsManager
.lightGrayColor,
)),
),
),
const DataCell(SizedBox()),
const DataCell(SizedBox()),
const DataCell(SizedBox()),
])
]
: List.generate(state.tags.length, (index) {
final tag = state.tags[index];
final controller = controllers[index];
final availableTags = getAvailableTags(
allTags ?? [], state.tags, tag);
return DataRow(
cells: [
DataCell(Text((index + 1).toString())),
DataCell(
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
tag.product?.name ?? 'Unknown',
overflow: TextOverflow.ellipsis,
)),
const SizedBox(width: 10),
Container(
width: 20.0,
height: 20.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager
.lightGrayColor,
width: 1.0,
),
),
child: IconButton(
icon: const Icon(
Icons.close,
color: ColorsManager
.lightGreyColor,
size: 16,
),
onPressed: () {
context
.read<AssignTagBloc>()
.add(DeleteTag(
tagToDelete: tag,
tags: state.tags));
},
tooltip: 'Delete Tag',
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(),
),
),
],
),
),
DataCell(
Container(
alignment: Alignment
.centerLeft, // Align cell content to the left
child: SizedBox(
width: double
.infinity, // Ensure full width for dropdown
child: DialogTextfieldDropdown(
items: availableTags,
initialValue: tag.tag,
onSelected: (value) {
controller.text = value;
context
.read<AssignTagBloc>()
.add(UpdateTagEvent(
index: index,
tag: value.trim(),
));
},
),
),
),
),
DataCell(
SizedBox(
width: double.infinity,
child: DialogDropdown(
items: locations,
selectedValue:
tag.location ?? 'Main Space',
onSelected: (value) {
context
.read<AssignTagBloc>()
.add(UpdateLocation(
index: index,
location: value,
));
},
)),
),
],
);
}),
),
),
if (state.errorMessage != null)
Text(state.errorMessage!,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.warningRed)),
],
),
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const SizedBox(width: 10),
Expanded(
child: Builder(
builder: (buttonContext) => CancelButton(
label: 'Add New Device',
onPressed: () async {
final updatedTags = List<Tag>.from(state.tags);
final result =
TagHelper.processTags(updatedTags, subspaces);
final processedTags =
result['updatedTags'] as List<Tag>;
final processedSubspaces = List<SubspaceModel>.from(
result['subspaces'] as List<dynamic>);
Navigator.of(context).pop();
await showDialog(
context: context,
builder: (context) => AddDeviceTypeWidget(
products: products,
subspaces: processedSubspaces,
initialSelectedProducts: TagHelper
.createInitialSelectedProductsForTags(
processedTags, processedSubspaces),
spaceName: spaceName,
spaceTags: processedTags,
isCreate: false,
onSave: onSave,
),
);
},
),
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
borderRadius: 10,
backgroundColor: state.isSaveEnabled
? ColorsManager.secondaryColor
: ColorsManager.grayColor,
foregroundColor: ColorsManager.whiteColors,
onPressed: state.isSaveEnabled
? () async {
final updatedTags = List<Tag>.from(state.tags);
final result = TagHelper.processTags(
updatedTags, subspaces);
final processedTags =
result['updatedTags'] as List<Tag>;
final processedSubspaces =
List<SubspaceModel>.from(
result['subspaces'] as List<dynamic>);
onSave?.call(processedTags, processedSubspaces);
Navigator.of(context).pop();
}
: null,
child: const Text('Save'),
),
),
const SizedBox(width: 10),
],
),
],
);
} else if (state is AssignTagLoading) {
return const Center(child: CircularProgressIndicator());
} else {
return const Center(child: Text('Something went wrong.'));
}
},
),
);
}
List<String> getAvailableTags(
List<String> allTags, List<Tag> currentTags, Tag currentTag) {
List<String> availableTagsForTagModel = TagHelper.getAvailableTags<Tag>(
allTags: allTags,
currentTags: currentTags,
currentTag: currentTag,
getTag: (tag) => tag.tag ?? '',
);
return availableTagsForTagModel;
}
}

View File

@ -40,21 +40,20 @@ class AssignTagModelBloc
(index) => TagModel(
tag: '',
product: selectedProduct.product,
location: 'None',
location: 'Main Space',
),
));
}
}
emit(AssignTagModelLoaded(
tags: allTags,
isSaveEnabled: _validateTags(allTags),
));
tags: allTags,
isSaveEnabled: _validateTags(allTags),
errorMessage: ''));
});
on<UpdateTag>((event, emit) {
final currentState = state;
if (currentState is AssignTagModelLoaded &&
currentState.tags.isNotEmpty) {
final tags = List<TagModel>.from(currentState.tags);
@ -122,17 +121,20 @@ class AssignTagModelBloc
}
bool _validateTags(List<TagModel> tags) {
if (tags.isEmpty) {
return false;
}
final uniqueTags = tags.map((tag) => tag.tag?.trim() ?? '').toSet();
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
return uniqueTags.length == tags.length && !hasEmptyTag;
final isValid = uniqueTags.length == tags.length && !hasEmptyTag;
return isValid;
}
String? _getValidationError(List<TagModel> tags) {
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
if (hasEmptyTag) return 'Tags cannot be empty.';
if (hasEmptyTag) {
return 'Tags cannot be empty.';
}
// Check for duplicate tags
final duplicateTags = tags
.map((tag) => tag.tag?.trim() ?? '')
.fold<Map<String, int>>({}, (map, tag) {

View File

@ -10,16 +10,16 @@ abstract class AssignTagModelEvent extends Equatable {
}
class InitializeTagModels extends AssignTagModelEvent {
final List<TagModel>? initialTags;
final List<TagModel> initialTags;
final List<SelectedProduct> addedProducts;
const InitializeTagModels({
required this.initialTags,
this.initialTags = const [],
required this.addedProducts,
});
@override
List<Object> get props => [initialTags ?? [], addedProducts];
List<Object> get props => [initialTags, addedProducts];
}
class UpdateTag extends AssignTagModelEvent {

View File

@ -5,7 +5,7 @@ abstract class AssignTagModelState extends Equatable {
const AssignTagModelState();
@override
List<Object> get props => [];
List<Object?> get props => [];
}
class AssignTagModelInitial extends AssignTagModelState {}
@ -15,7 +15,7 @@ class AssignTagModelLoading extends AssignTagModelState {}
class AssignTagModelLoaded extends AssignTagModelState {
final List<TagModel> tags;
final bool isSaveEnabled;
final String? errorMessage;
final String? errorMessage;
const AssignTagModelLoaded({
required this.tags,
@ -24,7 +24,7 @@ class AssignTagModelLoaded extends AssignTagModelState {
});
@override
List<Object> get props => [tags, isSaveEnabled];
List<Object?> get props => [tags, isSaveEnabled, errorMessage];
}
class AssignTagModelError extends AssignTagModelState {
@ -33,5 +33,5 @@ class AssignTagModelError extends AssignTagModelState {
const AssignTagModelError(this.errorMessage);
@override
List<Object> get props => [errorMessage];
List<Object?> get props => [errorMessage];
}

View File

@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/dialog_dropdown.dart';
import 'package:syncrow_web/common/dialog_textfield_dropdown.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
@ -11,354 +13,355 @@ import 'package:syncrow_web/pages/spaces_management/space_model/models/space_tem
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
class AssignTagModelsDialog extends StatelessWidget {
final List<ProductModel>? products;
final List<SubspaceTemplateModel>? subspaces;
final List<TagModel>? initialTags;
final SpaceTemplateModel? spaceModel;
final List<TagModel> initialTags;
final ValueChanged<List<TagModel>>? onTagsAssigned;
final List<SelectedProduct> addedProducts;
final List<String>? allTags;
final String spaceName;
final String title;
final BuildContext? pageContext;
final List<String>? otherSpaceModels;
final List<SpaceTemplateModel>? allSpaceModels;
const AssignTagModelsDialog({
Key? key,
required this.products,
required this.subspaces,
required this.addedProducts,
this.initialTags,
this.onTagsAssigned,
this.allTags,
required this.spaceName,
required this.title
}) : super(key: key);
const AssignTagModelsDialog(
{Key? key,
required this.products,
required this.subspaces,
required this.addedProducts,
required this.initialTags,
this.onTagsAssigned,
this.allTags,
required this.spaceName,
required this.title,
this.pageContext,
this.otherSpaceModels,
this.spaceModel,
this.allSpaceModels})
: super(key: key);
@override
Widget build(BuildContext context) {
final List<String> locations =
(subspaces ?? []).map((subspace) => subspace.subspaceName).toList();
final List<String> locations = (subspaces ?? [])
.map((subspace) => subspace.subspaceName)
.toList()
..add('Main Space');
return BlocProvider(
create: (_) => AssignTagModelBloc()
..add(InitializeTagModels(
initialTags: initialTags,
addedProducts: addedProducts,
)),
child: BlocBuilder<AssignTagModelBloc, AssignTagModelState>(
builder: (context, state) {
if (state is AssignTagModelLoaded) {
final controllers = List.generate(
state.tags.length,
(index) => TextEditingController(text: state.tags[index].tag),
);
create: (_) => AssignTagModelBloc()
..add(InitializeTagModels(
initialTags: initialTags,
addedProducts: addedProducts,
)),
child: BlocListener<AssignTagModelBloc, AssignTagModelState>(
listener: (context, state) {},
child: BlocBuilder<AssignTagModelBloc, AssignTagModelState>(
builder: (context, state) {
if (state is AssignTagModelLoaded) {
final controllers = List.generate(
state.tags.length,
(index) => TextEditingController(text: state.tags[index].tag),
);
return AlertDialog(
title: Text(title),
backgroundColor: ColorsManager.whiteColors,
content: SingleChildScrollView(
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(20),
child: DataTable(
headingRowColor: WidgetStateProperty.all(
ColorsManager.dataHeaderGrey),
border: TableBorder.all(
color: ColorsManager.dataHeaderGrey,
width: 1,
return AlertDialog(
title: Text(title),
backgroundColor: ColorsManager.whiteColors,
content: SingleChildScrollView(
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(20),
),
columns: [
DataColumn(
label: Text('#',
style:
Theme.of(context).textTheme.bodyMedium)),
DataColumn(
label: Text('Device',
style:
Theme.of(context).textTheme.bodyMedium)),
DataColumn(
label: Text('Tag',
style:
Theme.of(context).textTheme.bodyMedium)),
DataColumn(
label: Text('Location',
style:
Theme.of(context).textTheme.bodyMedium)),
],
rows: state.tags.isEmpty
? [
const DataRow(cells: [
DataCell(
Center(
child: Text(
'No Data Available',
style: TextStyle(
fontSize: 14,
color: ColorsManager.lightGrayColor,
),
),
),
),
DataCell(SizedBox()),
DataCell(SizedBox()),
DataCell(SizedBox()),
])
]
: List.generate(state.tags.length, (index) {
final tag = state.tags[index];
final controller = controllers[index];
return DataRow(
cells: [
DataCell(Text(index.toString())),
DataCell(
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
tag.product?.name ?? 'Unknown',
overflow: TextOverflow.ellipsis,
)),
IconButton(
icon: const Icon(Icons.close,
color: ColorsManager.warningRed,
size: 16),
onPressed: () {
context
.read<AssignTagModelBloc>()
.add(DeleteTagModel(
tagToDelete: tag,
tags: state.tags));
},
tooltip: 'Delete Tag',
)
],
),
),
DataCell(
Row(
children: [
Expanded(
child: TextFormField(
controller: controller,
onChanged: (value) {
context
.read<AssignTagModelBloc>()
.add(UpdateTag(
index: index,
tag: value.trim(),
));
},
decoration: const InputDecoration(
hintText: 'Enter Tag',
border: InputBorder.none,
),
style: const TextStyle(
fontSize: 14,
color: ColorsManager.blackColor,
),
),
),
SizedBox(
width: MediaQuery.of(context)
.size
.width *
0.15,
child: PopupMenuButton<String>(
color: ColorsManager.whiteColors,
icon: const Icon(
Icons.arrow_drop_down,
color: ColorsManager.blackColor),
onSelected: (value) {
controller.text = value;
context
.read<AssignTagModelBloc>()
.add(UpdateTag(
index: index,
tag: value,
));
},
itemBuilder: (context) {
return (allTags ?? [])
.where((tagValue) => !state
.tags
.map((e) => e.tag)
.contains(tagValue))
.map((tagValue) {
return PopupMenuItem<String>(
textStyle: const TextStyle(
color: ColorsManager
.textPrimaryColor),
value: tagValue,
child: ConstrainedBox(
constraints:
BoxConstraints(
minWidth: MediaQuery.of(
context)
.size
.width *
0.15,
maxWidth: MediaQuery.of(
context)
.size
.width *
0.15,
),
child: Text(
tagValue,
overflow: TextOverflow
.ellipsis,
),
));
}).toList();
},
),
),
],
),
),
DataCell(
DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: tag.location ?? 'None',
dropdownColor: ColorsManager
.whiteColors, // Dropdown background
style: const TextStyle(
color: Colors
.black), // Style for selected text
items: [
const DropdownMenuItem<String>(
value: 'None',
child: Text(
'None',
style: TextStyle(
color: ColorsManager
.textPrimaryColor),
),
),
...locations.map((location) {
return DropdownMenuItem<String>(
value: location,
child: Text(
location,
style: const TextStyle(
color: ColorsManager
.textPrimaryColor),
),
);
}).toList(),
],
onChanged: (value) {
if (value != null) {
context
.read<AssignTagModelBloc>()
.add(UpdateLocation(
index: index,
location: value,
));
}
},
),
),
),
],
);
}),
),
),
if (state.errorMessage != null)
Text(
state.errorMessage!,
style: const TextStyle(color: ColorsManager.warningRed),
),
],
),
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const SizedBox(width: 10),
Expanded(
child: CancelButton(
label: 'Cancel',
onPressed: () async {
Navigator.of(context).pop();
await showDialog(
barrierDismissible: false,
context: context,
builder: (context) => CreateSpaceModelDialog(
products: products,
allTags: allTags,
spaceModel: SpaceTemplateModel(
modelName: spaceName,
subspaceModels: subspaces,
tags: initialTags),
child: DataTable(
headingRowColor: WidgetStateProperty.all(
ColorsManager.dataHeaderGrey),
border: TableBorder.all(
color: ColorsManager.dataHeaderGrey,
width: 1,
borderRadius: BorderRadius.circular(20),
),
);
},
),
columns: [
DataColumn(
label: Text('#',
style: Theme.of(context)
.textTheme
.bodyMedium)),
DataColumn(
label: Text('Device',
style: Theme.of(context)
.textTheme
.bodyMedium)),
DataColumn(
numeric: false,
label: Text('Tag',
style: Theme.of(context)
.textTheme
.bodyMedium)),
DataColumn(
label: Text('Location',
style: Theme.of(context)
.textTheme
.bodyMedium)),
],
rows: state.tags.isEmpty
? [
DataRow(cells: [
DataCell(
Center(
child: Text('No Devices Available',
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: ColorsManager
.lightGrayColor,
)),
),
),
const DataCell(SizedBox()),
const DataCell(SizedBox()),
const DataCell(SizedBox()),
])
]
: List.generate(state.tags.length, (index) {
final tag = state.tags[index];
final controller = controllers[index];
final availableTags =
TagHelper.getAvailableTagModels(
allTags ?? [], state.tags, tag);
return DataRow(
cells: [
DataCell(Text((index + 1).toString())),
DataCell(
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
tag.product?.name ?? 'Unknown',
overflow: TextOverflow.ellipsis,
)),
const SizedBox(width: 10),
Container(
width: 20.0,
height: 20.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager
.lightGrayColor,
width: 1.0,
),
),
child: IconButton(
icon: const Icon(
Icons.close,
color: ColorsManager
.lightGreyColor,
size: 16,
),
onPressed: () {
context
.read<
AssignTagModelBloc>()
.add(DeleteTagModel(
tagToDelete: tag,
tags: state.tags));
},
tooltip: 'Delete Tag',
padding: EdgeInsets.zero,
constraints:
const BoxConstraints(),
),
),
],
),
),
DataCell(
Container(
alignment: Alignment
.centerLeft, // Align cell content to the left
child: SizedBox(
width: double
.infinity, // Ensure full width for dropdown
child: DialogTextfieldDropdown(
items: availableTags,
initialValue: tag.tag,
onSelected: (value) {
controller.text = value;
context
.read<
AssignTagModelBloc>()
.add(UpdateTag(
index: index,
tag: value,
));
},
),
),
),
),
DataCell(
SizedBox(
width: double.infinity,
child: DialogDropdown(
items: locations,
selectedValue: tag.location ??
'Main Space',
onSelected: (value) {
context
.read<
AssignTagModelBloc>()
.add(UpdateLocation(
index: index,
location: value,
));
},
)),
),
],
);
}),
),
),
if (state.errorMessage != null)
Text(state.errorMessage!,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.warningRed)),
],
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
borderRadius: 10,
backgroundColor: state.isSaveEnabled
? ColorsManager.secondaryColor
: ColorsManager.grayColor,
foregroundColor: ColorsManager.whiteColors,
onPressed: state.isSaveEnabled
? () async {
Navigator.of(context).pop();
final assignedTags = <TagModel>{};
for (var tag in state.tags) {
if (tag.location == null ||
subspaces == null) {
continue;
}
for (var subspace in subspaces!) {
if (tag.location == subspace.subspaceName) {
subspace.tags ??= [];
subspace.tags!.add(tag);
assignedTags.add(tag);
break;
}
}
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const SizedBox(width: 10),
Expanded(
child: Builder(
builder: (buttonContext) => CancelButton(
label: 'Add New Device',
onPressed: () async {
final updatedTags =
List<TagModel>.from(state.tags);
final result =
TagHelper.updateSubspaceTagModels(
updatedTags, subspaces);
final processedTags =
result['updatedTags'] as List<TagModel>;
final processedSubspaces =
List<SubspaceTemplateModel>.from(
result['subspaces'] as List<dynamic>);
if (context.mounted) {
Navigator.of(context).pop();
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (dialogContext) =>
AddDeviceTypeModelWidget(
products: products,
subspaces: processedSubspaces,
isCreate: false,
initialSelectedProducts: TagHelper
.createInitialSelectedProducts(
processedTags,
processedSubspaces),
allTags: allTags,
spaceName: spaceName,
otherSpaceModels: otherSpaceModels,
spaceTagModels: processedTags,
pageContext: pageContext,
spaceModel: SpaceTemplateModel(
modelName: spaceName,
tags: updatedTags,
uuid: spaceModel?.uuid,
internalId:
spaceModel?.internalId,
subspaceModels:
processedSubspaces)),
);
}
state.tags.removeWhere(assignedTags.contains);
await showDialog(
barrierDismissible: false,
context: context,
builder: (context) => CreateSpaceModelDialog(
products: products,
allTags: allTags,
spaceModel: SpaceTemplateModel(
modelName: spaceName,
subspaceModels: subspaces,
tags: state.tags),
),
);
}
: null,
child: const Text('Save'),
),
},
),
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
borderRadius: 10,
backgroundColor: state.isSaveEnabled
? ColorsManager.secondaryColor
: ColorsManager.grayColor,
foregroundColor: ColorsManager.whiteColors,
onPressed: state.isSaveEnabled
? () async {
final updatedTags =
List<TagModel>.from(state.tags);
final result =
TagHelper.updateSubspaceTagModels(
updatedTags, subspaces);
final processedTags =
result['updatedTags'] as List<TagModel>;
final processedSubspaces =
List<SubspaceTemplateModel>.from(
result['subspaces']
as List<dynamic>);
Navigator.of(context)
.popUntil((route) => route.isFirst);
await showDialog(
context: context,
builder: (BuildContext dialogContext) {
return CreateSpaceModelDialog(
products: products,
allSpaceModels: allSpaceModels,
allTags: allTags,
pageContext: pageContext,
otherSpaceModels: otherSpaceModels,
spaceModel: SpaceTemplateModel(
modelName: spaceName,
tags: processedTags,
uuid: spaceModel?.uuid,
internalId:
spaceModel?.internalId,
subspaceModels:
processedSubspaces),
);
},
);
}
: null,
child: const Text('Save'),
),
),
const SizedBox(width: 10),
],
),
const SizedBox(width: 10),
],
),
],
);
} else if (state is AssignTagModelLoading) {
return const Center(child: CircularProgressIndicator());
} else {
return const Center(child: Text('Something went wrong.'));
}
},
),
);
);
} else if (state is AssignTagModelLoading) {
return const Center(child: CircularProgressIndicator());
} else {
return const Center(child: Text('Something went wrong.'));
}
},
),
));
}
}

View File

@ -77,9 +77,7 @@ class CreateCommunityDialog extends StatelessWidget {
.read<CommunityDialogBloc>()
.add(ValidateCommunityNameEvent(value));
},
style: const TextStyle(
color: ColorsManager.blackColor,
),
style: Theme.of(context).textTheme.bodyMedium,
decoration: InputDecoration(
hintText: 'Please enter the community name',
filled: true,

View File

@ -0,0 +1,110 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';
import 'subspace_event.dart';
import 'subspace_state.dart';
class SubSpaceBloc extends Bloc<SubSpaceEvent, SubSpaceState> {
SubSpaceBloc() : super(SubSpaceState([], [], '', {})) {
on<AddSubSpace>((event, emit) {
final existingNames = state.subSpaces.map((e) => e.subspaceName).toSet();
if (existingNames.contains(event.subSpace.subspaceName.toLowerCase())) {
final updatedDuplicates = Set<String>.from(state.duplicates)
..add(event.subSpace.subspaceName.toLowerCase());
final updatedSubSpaces = List<SubspaceModel>.from(state.subSpaces)
..add(event.subSpace);
emit(SubSpaceState(
updatedSubSpaces,
state.updatedSubSpaceModels,
'*Duplicated sub-space name',
updatedDuplicates,
));
} else {
// Add subspace if no duplicate exists
final updatedSubSpaces = List<SubspaceModel>.from(state.subSpaces)
..add(event.subSpace);
if (state.duplicates.isNotEmpty) {
emit(SubSpaceState(
updatedSubSpaces,
state.updatedSubSpaceModels,
'*Duplicated sub-space name',
state.duplicates,
));
} else {
emit(SubSpaceState(
updatedSubSpaces,
state.updatedSubSpaceModels,
'',
state.duplicates,
// Clear error message
));
}
}
});
// Handle RemoveSubSpace Event
on<RemoveSubSpace>((event, emit) {
final updatedSubSpaces = List<SubspaceModel>.from(state.subSpaces)
..remove(event.subSpace);
final updatedSubspaceModels = List<UpdateSubspaceModel>.from(
state.updatedSubSpaceModels,
);
if (event.subSpace.uuid?.isNotEmpty ?? false) {
updatedSubspaceModels.add(UpdateSubspaceModel(
action: Action.delete,
uuid: event.subSpace.uuid!,
));
}
final nameOccurrences = <String, int>{};
for (final subSpace in updatedSubSpaces) {
final lowerName = subSpace.subspaceName.toLowerCase();
nameOccurrences[lowerName] = (nameOccurrences[lowerName] ?? 0) + 1;
}
final updatedDuplicates = nameOccurrences.entries
.where((entry) => entry.value > 1)
.map((entry) => entry.key)
.toSet();
final errorMessage =
updatedDuplicates.isNotEmpty ? '*Duplicated sub-space name' : '';
emit(SubSpaceState(
updatedSubSpaces,
updatedSubspaceModels,
errorMessage,
updatedDuplicates,
));
});
on<UpdateSubSpace>((event, emit) {
final updatedSubSpaces = state.subSpaces.map((subSpace) {
if (subSpace.uuid == event.updatedSubSpace.uuid) {
return event.updatedSubSpace;
}
return subSpace;
}).toList();
final updatedSubspaceModels = List<UpdateSubspaceModel>.from(
state.updatedSubSpaceModels,
);
updatedSubspaceModels.add(UpdateSubspaceModel(
action: Action.update,
uuid: event.updatedSubSpace.uuid!,
));
emit(SubSpaceState(
updatedSubSpaces,
updatedSubspaceModels,
'',
state.duplicates,
));
});
}
}

View File

@ -0,0 +1,18 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
abstract class SubSpaceEvent {}
class AddSubSpace extends SubSpaceEvent {
final SubspaceModel subSpace;
AddSubSpace(this.subSpace);
}
class RemoveSubSpace extends SubSpaceEvent {
final SubspaceModel subSpace;
RemoveSubSpace(this.subSpace);
}
class UpdateSubSpace extends SubSpaceEvent {
final SubspaceModel updatedSubSpace;
UpdateSubSpace(this.updatedSubSpace);
}

View File

@ -0,0 +1,29 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
class SubSpaceState {
final List<SubspaceModel> subSpaces;
final List<UpdateSubspaceModel> updatedSubSpaceModels;
final String errorMessage;
final Set<String> duplicates;
SubSpaceState(
this.subSpaces,
this.updatedSubSpaceModels,
this.errorMessage,
this.duplicates,
);
SubSpaceState copyWith({
List<SubspaceModel>? subSpaces,
List<UpdateSubspaceModel>? updatedSubSpaceModels,
String? errorMessage,
Set<String>? duplicates,
}) {
return SubSpaceState(
subSpaces ?? this.subSpaces,
updatedSubSpaceModels ?? this.updatedSubSpaceModels,
errorMessage ?? this.errorMessage,
duplicates ?? this.duplicates,
);
}
}

View File

@ -0,0 +1,228 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_state.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class CreateSubSpaceDialog extends StatelessWidget {
final bool isEdit;
final String dialogTitle;
final List<SubspaceModel>? existingSubSpaces;
final String? spaceName;
final List<Tag>? spaceTags;
final List<ProductModel>? products;
final Function(List<SubspaceModel>?)? onSave;
const CreateSubSpaceDialog(
{Key? key,
required this.isEdit,
required this.dialogTitle,
this.existingSubSpaces,
required this.spaceName,
required this.spaceTags,
required this.products,
required this.onSave})
: super(key: key);
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
final textController = TextEditingController();
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: BlocProvider(
create: (_) {
final bloc = SubSpaceBloc();
if (existingSubSpaces != null) {
for (var subSpace in existingSubSpaces!) {
bloc.add(AddSubSpace(subSpace));
}
}
return bloc;
},
child: BlocBuilder<SubSpaceBloc, SubSpaceState>(
builder: (context, state) {
return Container(
color: ColorsManager.whiteColors,
child: SizedBox(
width: screenWidth * 0.35,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
dialogTitle,
style: Theme.of(context)
.textTheme
.headlineLarge
?.copyWith(color: ColorsManager.blackColor),
),
const SizedBox(height: 16),
Container(
width: screenWidth * 0.35,
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 16.0),
decoration: BoxDecoration(
color: ColorsManager.boxColor,
borderRadius: BorderRadius.circular(10),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
...state.subSpaces.asMap().entries.map(
(entry) {
final index = entry.key;
final subSpace = entry.value;
final lowerName =
subSpace.subspaceName.toLowerCase();
final duplicateIndices = state.subSpaces
.asMap()
.entries
.where((e) =>
e.value.subspaceName.toLowerCase() ==
lowerName)
.map((e) => e.key)
.toList();
final isDuplicate =
duplicateIndices.length > 1 &&
duplicateIndices.indexOf(index) != 0;
return Chip(
label: Text(subSpace.subspaceName,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color:
ColorsManager.spaceColor)),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: isDuplicate
? ColorsManager.red
: ColorsManager.transparentColor,
width: 0,
),
),
deleteIcon: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager.lightGrayColor,
width: 1.5,
),
),
child: const Icon(
Icons.close,
size: 16,
color: ColorsManager.lightGrayColor,
),
),
onDeleted: () => context
.read<SubSpaceBloc>()
.add(RemoveSubSpace(subSpace)),
);
},
),
SizedBox(
width: 200,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: state.subSpaces.isEmpty
? 'Please enter the name'
: null,
hintStyle: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager
.lightGrayColor)),
onSubmitted: (value) {
if (value.trim().isNotEmpty) {
context.read<SubSpaceBloc>().add(
AddSubSpace(SubspaceModel(
subspaceName: value.trim(),
disabled: false)));
textController.clear();
}
},
style:
Theme.of(context).textTheme.bodyMedium),
),
],
),
),
if (state.errorMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(state.errorMessage,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager.warningRed,
)),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: CancelButton(
label: 'Cancel',
onPressed: () async {
Navigator.of(context).pop();
},
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
onPressed: (state.errorMessage.isNotEmpty)
? null
: () async {
final subSpaces = context
.read<SubSpaceBloc>()
.state
.subSpaces;
onSave!(subSpaces);
Navigator.of(context).pop();
},
backgroundColor: ColorsManager.secondaryColor,
borderRadius: 10,
foregroundColor: state.errorMessage.isNotEmpty
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
child: const Text('OK'),
),
),
],
),
],
),
),
));
},
),
),
);
}
}

View File

@ -6,35 +6,49 @@ import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_
import 'package:syncrow_web/utils/constants/action_enum.dart';
class SubSpaceModelBloc extends Bloc<SubSpaceModelEvent, SubSpaceModelState> {
SubSpaceModelBloc() : super(SubSpaceModelState([], [], '')) {
SubSpaceModelBloc() : super(SubSpaceModelState([], [], '', {})) {
// Handle AddSubSpaceModel Event
on<AddSubSpaceModel>((event, emit) {
// Check for duplicate names (case-insensitive)
final existingNames =
state.subSpaces.map((e) => e.subspaceName.toLowerCase()).toSet();
if (existingNames.contains(event.subSpace.subspaceName.toLowerCase())) {
// Emit state with an error message if duplicate name exists
final updatedDuplicates = Set<String>.from(state.duplicates)
..add(event.subSpace.subspaceName.toLowerCase());
final updatedSubSpaces =
List<SubspaceTemplateModel>.from(state.subSpaces)
..add(event.subSpace);
emit(SubSpaceModelState(
state.subSpaces,
updatedSubSpaces,
state.updatedSubSpaceModels,
'Subspace name already exists.',
'*Duplicated sub-space name',
updatedDuplicates,
));
} else {
// Add subspace if no duplicate exists
final updatedSubSpaces =
List<SubspaceTemplateModel>.from(state.subSpaces)
..add(event.subSpace);
emit(SubSpaceModelState(
updatedSubSpaces,
state.updatedSubSpaceModels,
'', // Clear error message
));
if (state.duplicates.isNotEmpty) {
emit(SubSpaceModelState(
updatedSubSpaces,
state.updatedSubSpaceModels,
'*Duplicated sub-space name',
state.duplicates,
));
} else {
emit(SubSpaceModelState(
updatedSubSpaces,
state.updatedSubSpaceModels,
'',
state.duplicates,
));
}
}
});
// Handle RemoveSubSpaceModel Event
on<RemoveSubSpaceModel>((event, emit) {
final updatedSubSpaces = List<SubspaceTemplateModel>.from(state.subSpaces)
..remove(event.subSpace);
@ -50,10 +64,28 @@ class SubSpaceModelBloc extends Bloc<SubSpaceModelEvent, SubSpaceModelState> {
));
}
// Count occurrences of sub-space names to identify duplicates
final nameOccurrences = <String, int>{};
for (final subSpace in updatedSubSpaces) {
final lowerName = subSpace.subspaceName.toLowerCase();
nameOccurrences[lowerName] = (nameOccurrences[lowerName] ?? 0) + 1;
}
// Identify duplicate names
final updatedDuplicates = nameOccurrences.entries
.where((entry) => entry.value > 1)
.map((entry) => entry.key)
.toSet();
// Determine the error message
final errorMessage =
updatedDuplicates.isNotEmpty ? '*Duplicated sub-space name' : '';
emit(SubSpaceModelState(
updatedSubSpaces,
updatedSubspaceModels,
'', // Clear error message
errorMessage,
updatedDuplicates,
));
});
@ -78,7 +110,9 @@ class SubSpaceModelBloc extends Bloc<SubSpaceModelEvent, SubSpaceModelState> {
emit(SubSpaceModelState(
updatedSubSpaces,
updatedSubspaceModels,
'', // Clear error message
'',
state.duplicates,
// Clear error message
));
});
}

View File

@ -5,22 +5,26 @@ class SubSpaceModelState {
final List<SubspaceTemplateModel> subSpaces;
final List<UpdateSubspaceTemplateModel> updatedSubSpaceModels;
final String errorMessage;
final Set<String> duplicates;
SubSpaceModelState(
this.subSpaces,
this.updatedSubSpaceModels,
this.errorMessage,
this.duplicates,
);
SubSpaceModelState copyWith({
List<SubspaceTemplateModel>? subSpaces,
List<UpdateSubspaceTemplateModel>? updatedSubSpaceModels,
String? errorMessage,
Set<String>? duplicates,
}) {
return SubSpaceModelState(
subSpaces ?? this.subSpaces,
updatedSubSpaceModels ?? this.updatedSubSpaceModels,
errorMessage ?? this.errorMessage,
duplicates ?? this.duplicates,
);
}
}

View File

@ -2,37 +2,25 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class CreateSubSpaceModelDialog extends StatelessWidget {
final bool isEdit;
final String dialogTitle;
final List<SubspaceTemplateModel>? existingSubSpaces;
final String? spaceName;
final List<TagModel>? spaceTagModels;
final List<String>? allTags;
final List<ProductModel>? products;
final SpaceTemplateModel? spaceModel;
final void Function(List<SubspaceTemplateModel> newSubspaces)? onUpdate;
const CreateSubSpaceModelDialog({
Key? key,
required this.isEdit,
required this.dialogTitle,
this.existingSubSpaces,
required this.allTags,
required this.spaceName,
required this.spaceTagModels,
required this.products,
required this.spaceModel,
}) : super(key: key);
const CreateSubSpaceModelDialog(
{Key? key,
required this.isEdit,
required this.dialogTitle,
this.existingSubSpaces,
this.onUpdate})
: super(key: key);
@override
Widget build(BuildContext context) {
@ -58,7 +46,7 @@ class CreateSubSpaceModelDialog extends StatelessWidget {
return Container(
color: ColorsManager.whiteColors,
child: SizedBox(
width: screenWidth * 0.35,
width: screenWidth * 0.3,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
@ -85,82 +73,111 @@ class CreateSubSpaceModelDialog extends StatelessWidget {
spacing: 8.0,
runSpacing: 8.0,
children: [
...state.subSpaces.map(
(subSpace) => Chip(
label: Text(
subSpace.subspaceName,
style: const TextStyle(
color: ColorsManager.spaceColor),
),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(
color: ColorsManager.transparentColor,
width: 0,
),
),
deleteIcon: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager.lightGrayColor,
width: 1.5,
...state.subSpaces.asMap().entries.map(
(entry) {
final index = entry.key;
final subSpace = entry.value;
final lowerName =
subSpace.subspaceName.toLowerCase();
final duplicateIndices = state.subSpaces
.asMap()
.entries
.where((e) =>
e.value.subspaceName.toLowerCase() ==
lowerName)
.map((e) => e.key)
.toList();
final isDuplicate =
duplicateIndices.length > 1 &&
duplicateIndices.indexOf(index) != 0;
return Chip(
label: Text(subSpace.subspaceName,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager.spaceColor,
)),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: isDuplicate
? ColorsManager.red
: ColorsManager.transparentColor,
width: 0,
),
),
child: const Icon(
Icons.close,
size: 16,
color: ColorsManager.lightGrayColor,
deleteIcon: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager.lightGrayColor,
width: 1.5,
),
),
child: const Icon(
Icons.close,
size: 16,
color: ColorsManager.lightGrayColor,
),
),
),
onDeleted: () => context
.read<SubSpaceModelBloc>()
.add(RemoveSubSpaceModel(subSpace)),
),
onDeleted: () => context
.read<SubSpaceModelBloc>()
.add(RemoveSubSpaceModel(subSpace)),
);
},
),
SizedBox(
width: 200,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: state.subSpaces.isEmpty
? 'Please enter the name'
: null,
hintStyle: const TextStyle(
color: ColorsManager.lightGrayColor),
),
onSubmitted: (value) {
if (value.trim().isNotEmpty) {
context.read<SubSpaceModelBloc>().add(
AddSubSpaceModel(
SubspaceTemplateModel(
subspaceName: value.trim(),
disabled: false)));
textController.clear();
}
},
style: const TextStyle(
color: ColorsManager.blackColor),
),
controller: textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: state.subSpaces.isEmpty
? 'Please enter the name'
: null,
hintStyle: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(
color: ColorsManager
.lightGrayColor)),
onSubmitted: (value) {
if (value.trim().isNotEmpty) {
context.read<SubSpaceModelBloc>().add(
AddSubSpaceModel(
SubspaceTemplateModel(
subspaceName: value.trim(),
disabled: false)));
textController.clear();
}
},
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: ColorsManager.blackColor)),
),
if (state.errorMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
state.errorMessage,
style: const TextStyle(
color: ColorsManager.warningRed,
fontSize: 12,
),
),
),
],
),
),
if (state.errorMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Text(state.errorMessage,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager.red,
)),
),
const SizedBox(height: 16),
Row(
children: [
@ -169,51 +186,29 @@ class CreateSubSpaceModelDialog extends StatelessWidget {
label: 'Cancel',
onPressed: () async {
Navigator.of(context).pop();
await showDialog(
barrierDismissible: false,
context: context,
builder: (context) =>
CreateSpaceModelDialog(
products: products,
allTags: allTags,
spaceModel: SpaceTemplateModel(
modelName: spaceName ?? '',
subspaceModels: existingSubSpaces,
tags: spaceTagModels,
),
),
);
},
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
onPressed: () async {
final subSpaces = context
.read<SubSpaceModelBloc>()
.state
.subSpaces;
Navigator.of(context).pop();
await showDialog(
barrierDismissible: false,
context: context,
builder: (context) =>
CreateSpaceModelDialog(
products: products,
allTags: allTags,
spaceModel: SpaceTemplateModel(
modelName: spaceName ?? '',
subspaceModels: subSpaces,
tags: spaceTagModels,
),
),
);
},
onPressed: (state.errorMessage.isNotEmpty)
? null
: () async {
final subSpaces = context
.read<SubSpaceModelBloc>()
.state
.subSpaces;
Navigator.of(context).pop();
if (onUpdate != null) {
onUpdate!(subSpaces);
}
},
backgroundColor: ColorsManager.secondaryColor,
borderRadius: 10,
foregroundColor: ColorsManager.whiteColors,
foregroundColor: state.errorMessage.isNotEmpty
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
child: const Text('OK'),
),
),

View File

@ -0,0 +1,21 @@
import 'dart:ui';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/connection_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
class ConnectionHelper {
static Offset getCenterPosition(Size screenSize) {
return Offset(
screenSize.width / 2 - 260,
screenSize.height / 2 - 200,
);
}
static bool isHighlightedConnection(
Connection connection, SpaceModel? selectedSpace) {
if (selectedSpace == null) return true;
return connection.startSpace == selectedSpace ||
connection.endSpace == selectedSpace;
}
}

View File

@ -0,0 +1,61 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
class SpaceHelper {
static SpaceModel? findSpaceByUuid(
String? uuid, List<CommunityModel> communities) {
for (var community in communities) {
for (var space in community.spaces) {
if (space.uuid == uuid) return space;
}
}
return null;
}
static SpaceModel? findSpaceByInternalId(
String? internalId, List<SpaceModel> spaces) {
if (internalId != null) {
for (var space in spaces) {
if (space.internalId == internalId) return space;
}
}
return null;
}
static String generateUniqueSpaceName(
String originalName, List<SpaceModel> spaces) {
final baseName = originalName.replaceAll(RegExp(r'\(\d+\)$'), '').trim();
int maxNumber = 0;
for (var space in spaces) {
final match = RegExp(r'^(.*?)\((\d+)\)$').firstMatch(space.name);
if (match != null && match.group(1)?.trim() == baseName) {
int existingNumber = int.parse(match.group(2)!);
if (existingNumber > maxNumber) {
maxNumber = existingNumber;
}
}
}
return "$baseName(${maxNumber + 1})";
}
static bool isSave(List<SpaceModel> spaces) {
return spaces.isNotEmpty &&
spaces.any((space) =>
space.status == SpaceStatus.newSpace ||
space.status == SpaceStatus.modified ||
space.status == SpaceStatus.deleted);
}
static bool isHighlightedSpace(SpaceModel space, SpaceModel? selectedSpace) {
if (selectedSpace == null) return true;
return space == selectedSpace ||
selectedSpace.parent?.internalId == space.internalId ||
selectedSpace.children
?.any((child) => child.internalId == space.internalId) ==
true;
}
}

View File

@ -0,0 +1,364 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/base_tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
class TagHelper {
static Map<String, dynamic> updateTags<T>({
required List<T> updatedTags,
required List<dynamic>? subspaces,
required String Function(T) getInternalId,
required String? Function(T) getLocation,
required void Function(T, String) setLocation,
required String Function(dynamic) getSubspaceName,
required List<T>? Function(dynamic) getSubspaceTags,
required void Function(dynamic, List<T>?) setSubspaceTags,
required int? Function(T, List<dynamic>) checkTagExistInSubspace,
}) {
final modifiedTags = List<T>.from(updatedTags);
final modifiedSubspaces = List<dynamic>.from(subspaces ?? []);
if (subspaces != null) {
for (var subspace in subspaces) {
getSubspaceTags(subspace)?.removeWhere(
(tag) => !modifiedTags.any(
(updatedTag) => getInternalId(updatedTag) == getInternalId(tag)),
);
}
}
for (var tag in modifiedTags.toList()) {
if (modifiedSubspaces.isEmpty) continue;
final prevIndice = checkTagExistInSubspace(tag, modifiedSubspaces);
final tagLocation = getLocation(tag);
if ((tagLocation == 'Main Space' || tagLocation == null) &&
(prevIndice == null ||
getSubspaceName(modifiedSubspaces[prevIndice]) == 'Main Space')) {
continue;
}
if ((tagLocation == 'Main Space' || tagLocation == null) &&
prevIndice != null) {
getSubspaceTags(modifiedSubspaces[prevIndice])
?.removeWhere((t) => getInternalId(t) == getInternalId(tag));
continue;
}
if ((tagLocation != 'Main Space' && tagLocation != null) &&
prevIndice == null) {
final newIndex = modifiedSubspaces
.indexWhere((subspace) => getSubspaceName(subspace) == tagLocation);
if (newIndex != -1) {
if (getSubspaceTags(modifiedSubspaces[newIndex])
?.any((t) => getInternalId(t) == getInternalId(tag)) !=
true) {
setLocation(tag, getSubspaceName(modifiedSubspaces[newIndex]));
final subspaceTags =
getSubspaceTags(modifiedSubspaces[newIndex]) ?? [];
subspaceTags.add(tag);
setSubspaceTags(modifiedSubspaces[newIndex], subspaceTags);
}
}
modifiedTags.removeWhere((t) => getInternalId(t) == getInternalId(tag));
continue;
}
if ((tagLocation != 'Main Space' && tagLocation != null) &&
tagLocation != getSubspaceName(modifiedSubspaces[prevIndice!])) {
getSubspaceTags(modifiedSubspaces[prevIndice])
?.removeWhere((t) => getInternalId(t) == getInternalId(tag));
final newIndex = modifiedSubspaces
.indexWhere((subspace) => getSubspaceName(subspace) == tagLocation);
if (newIndex != -1) {
if (getSubspaceTags(modifiedSubspaces[newIndex])
?.any((t) => getInternalId(t) == getInternalId(tag)) !=
true) {
setLocation(tag, getSubspaceName(modifiedSubspaces[newIndex]));
final subspaceTags =
getSubspaceTags(modifiedSubspaces[newIndex]) ?? [];
subspaceTags.add(tag);
setSubspaceTags(modifiedSubspaces[newIndex], subspaceTags);
}
}
modifiedTags.removeWhere((t) => getInternalId(t) == getInternalId(tag));
continue;
}
if ((tagLocation != 'Main Space' && tagLocation != null) &&
tagLocation == getSubspaceName(modifiedSubspaces[prevIndice!])) {
modifiedTags.removeWhere((t) => getInternalId(t) == getInternalId(tag));
continue;
}
if ((tagLocation == 'Main Space' || tagLocation == null) &&
prevIndice != null) {
getSubspaceTags(modifiedSubspaces[prevIndice])
?.removeWhere((t) => getInternalId(t) == getInternalId(tag));
}
}
return {
'updatedTags': modifiedTags,
'subspaces': modifiedSubspaces,
};
}
static List<String> getAvailableTags<T>({
required List<String> allTags,
required List<T> currentTags,
required T currentTag,
required String? Function(T) getTag, // Allow nullable return type
}) {
return allTags
.where((tagValue) => !currentTags
.where((e) => e != currentTag) // Exclude the current row
.map((e) => getTag(e) ?? '') // Handle null values gracefully
.contains(tagValue))
.toList();
}
static List<String> getAvailableTagModels(
List<String> allTags, List<TagModel> currentTags, TagModel currentTag) {
List<String> availableTagsForTagModel =
TagHelper.getAvailableTags<TagModel>(
allTags: allTags,
currentTags: currentTags,
currentTag: currentTag,
getTag: (tag) => tag.tag ?? '',
);
return availableTagsForTagModel;
}
static List<TagModel> generateInitialTags({
List<TagModel>? spaceTagModels,
List<SubspaceTemplateModel>? subspaces,
}) {
final List<TagModel> initialTags = [];
if (spaceTagModels != null) {
initialTags.addAll(spaceTagModels);
}
if (subspaces != null) {
for (var subspace in subspaces) {
if (subspace.tags != null) {
initialTags.addAll(
subspace.tags!.map(
(tag) => tag.copyWith(
location: subspace.subspaceName,
internalId: tag.internalId,
tag: tag.tag,
),
),
);
}
}
}
return initialTags;
}
static List<Tag> generateInitialForTags({
List<Tag>? spaceTags,
List<SubspaceModel>? subspaces,
}) {
final List<Tag> initialTags = [];
if (spaceTags != null) {
initialTags.addAll(spaceTags);
}
if (subspaces != null) {
for (var subspace in subspaces) {
if (subspace.tags != null) {
initialTags.addAll(
subspace.tags!.map(
(tag) => tag.copyWith(
location: subspace.subspaceName,
internalId: tag.internalId,
tag: tag.tag,
),
),
);
}
}
}
return initialTags;
}
static Map<ProductModel, int> groupTags(List<BaseTag> tags) {
final Map<ProductModel, int> groupedTags = {};
for (var tag in tags) {
if (tag.product != null) {
final product = tag.product!;
groupedTags[product] = (groupedTags[product] ?? 0) + 1;
}
}
return groupedTags;
}
static List<SelectedProduct> createInitialSelectedProducts(
List<TagModel>? tags, List<SubspaceTemplateModel>? subspaces) {
final Map<ProductModel, int> productCounts = {};
if (tags != null) {
for (var tag in tags) {
if (tag.product != null) {
productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1;
}
}
}
if (subspaces != null) {
for (var subspace in subspaces) {
if (subspace.tags != null) {
for (var tag in subspace.tags!) {
if (tag.product != null) {
productCounts[tag.product!] =
(productCounts[tag.product!] ?? 0) + 1;
}
}
}
}
}
return productCounts.entries
.map((entry) => SelectedProduct(
productId: entry.key.uuid,
count: entry.value,
productName: entry.key.name ?? 'Unnamed',
product: entry.key,
))
.toList();
}
static List<SelectedProduct> createInitialSelectedProductsForTags(
List<Tag>? tags, List<SubspaceModel>? subspaces) {
final Map<ProductModel, int> productCounts = {};
if (tags != null) {
for (var tag in tags) {
if (tag.product != null) {
productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1;
}
}
}
if (subspaces != null) {
for (var subspace in subspaces) {
if (subspace.tags != null) {
for (var tag in subspace.tags!) {
if (tag.product != null) {
productCounts[tag.product!] =
(productCounts[tag.product!] ?? 0) + 1;
}
}
}
}
}
return productCounts.entries
.map((entry) => SelectedProduct(
productId: entry.key.uuid,
count: entry.value,
productName: entry.key.name ?? 'Unnamed',
product: entry.key,
))
.toList();
}
static int? checkTagExistInSubspaceModels(
TagModel tag, List<dynamic>? subspaces) {
if (subspaces == null) return null;
for (int i = 0; i < subspaces.length; i++) {
final subspace = subspaces[i] as SubspaceTemplateModel; // Explicit cast
if (subspace.tags == null) continue;
for (var t in subspace.tags!) {
if (tag.internalId == t.internalId) {
return i;
}
}
}
return null;
}
static Map<String, dynamic> updateSubspaceTagModels(
List<TagModel> updatedTags, List<SubspaceTemplateModel>? subspaces) {
return TagHelper.updateTags<TagModel>(
updatedTags: updatedTags,
subspaces: subspaces,
getInternalId: (tag) => tag.internalId,
getLocation: (tag) => tag.location,
setLocation: (tag, location) => tag.location = location,
getSubspaceName: (subspace) => subspace.subspaceName,
getSubspaceTags: (subspace) => subspace.tags,
setSubspaceTags: (subspace, tags) => subspace.tags = tags,
checkTagExistInSubspace: checkTagExistInSubspaceModels,
);
}
static int? checkTagExistInSubspace(Tag tag, List<dynamic>? subspaces) {
if (subspaces == null) return null;
for (int i = 0; i < subspaces.length; i++) {
final subspace = subspaces[i];
if (subspace.tags == null) continue;
for (var t in subspace.tags!) {
if (tag.internalId == t.internalId) {
return i;
}
}
}
return null;
}
static Map<String, dynamic> processTags(
List<Tag> updatedTags, List<SubspaceModel>? subspaces) {
return TagHelper.updateTags<Tag>(
updatedTags: updatedTags,
subspaces: subspaces,
getInternalId: (tag) => tag.internalId,
getLocation: (tag) => tag.location,
setLocation: (tag, location) => tag.location = location,
getSubspaceName: (subspace) => subspace.subspaceName,
getSubspaceTags: (subspace) => subspace.tags,
setSubspaceTags: (subspace, tags) => subspace.tags = tags,
checkTagExistInSubspace: checkTagExistInSubspace,
);
}
static List<String> getAllTagValues(
List<CommunityModel> communities, List<SpaceTemplateModel>? spaceModels) {
final Set<String> allTags = {};
if (spaceModels != null) {
for (var model in spaceModels) {
allTags.addAll(model.listAllTagValues());
}
}
for (final community in communities) {
for (final space in community.spaces) {
if (space.tags != null) {
allTags.addAll(space.listAllTagValues());
}
}
}
return allTags.toList();
}
}

View File

@ -0,0 +1,12 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_model_state.dart';
class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> {
SpaceModelBloc() : super(SpaceModelInitial()) {
on<SpaceModelSelectedEvent>((event, emit) {
emit(SpaceModelSelectedState(event.selectedIndex));
});
}
}

View File

@ -0,0 +1,7 @@
abstract class SpaceModelEvent {}
class SpaceModelSelectedEvent extends SpaceModelEvent {
final int selectedIndex;
SpaceModelSelectedEvent(this.selectedIndex);
}

View File

@ -0,0 +1,9 @@
abstract class SpaceModelState {}
class SpaceModelInitial extends SpaceModelState {}
class SpaceModelSelectedState extends SpaceModelState {
final int selectedIndex;
SpaceModelSelectedState(this.selectedIndex);
}

View File

@ -0,0 +1,130 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/space_model_card_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class LinkSpaceModelDialog extends StatelessWidget {
final Function(SpaceTemplateModel?)? onSave;
final int? initialSelectedIndex;
final List<SpaceTemplateModel> spaceModels;
const LinkSpaceModelDialog({
Key? key,
this.onSave,
this.initialSelectedIndex,
required this.spaceModels,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SpaceModelBloc()
..add(
SpaceModelSelectedEvent(initialSelectedIndex ?? -1),
),
child: Builder(
builder: (context) {
final bloc = context.read<SpaceModelBloc>();
return AlertDialog(
backgroundColor: ColorsManager.whiteColors,
title: const Text('Link a space model'),
content: spaceModels.isNotEmpty
? Container(
color: ColorsManager.textFieldGreyColor,
width: MediaQuery.of(context).size.width * 0.7,
height: MediaQuery.of(context).size.height * 0.6,
child: BlocBuilder<SpaceModelBloc, SpaceModelState>(
builder: (context, state) {
int selectedIndex = -1;
if (state is SpaceModelSelectedState) {
selectedIndex = state.selectedIndex;
}
return GridView.builder(
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: 3,
),
itemCount: spaceModels.length,
itemBuilder: (BuildContext context, int index) {
final model = spaceModels[index];
final isSelected = selectedIndex == index;
return GestureDetector(
onTap: () {
bloc.add(SpaceModelSelectedEvent(index));
},
child: Container(
margin: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(
color: isSelected
? ColorsManager.spaceColor
: Colors.transparent,
width: 2.0,
),
borderRadius: BorderRadius.circular(8.0),
),
child: SpaceModelCardWidget(model: model,),
),
);
},
);
},
),
)
: const Text('No space models available.'),
actions: [
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CancelButton(
onPressed: () {
Navigator.of(context).pop();
},
label: 'Cancel',
),
const SizedBox(width: 10),
BlocBuilder<SpaceModelBloc, SpaceModelState>(
builder: (context, state) {
final isEnabled = state is SpaceModelSelectedState &&
state.selectedIndex >= 0;
return SizedBox(
width: 140,
child: DefaultButton(
height: 40,
borderRadius: 10,
onPressed: isEnabled
? () {
if (onSave != null) {
final selectedModel =
spaceModels[state.selectedIndex];
onSave!(selectedModel);
}
Navigator.of(context).pop();
}
: null,
child: const Text('Save'),
),
);
},
),
],
),
),
],
);
},
),
);
}
}

View File

@ -3,8 +3,11 @@ import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_spac
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/create_space_template_body_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';
class CreateSpaceModelBloc
extends Bloc<CreateSpaceModelEvent, CreateSpaceModelState> {
@ -65,20 +68,108 @@ class CreateSpaceModelBloc
on<UpdateSpaceTemplate>((event, emit) {
_space = event.spaceTemplate;
emit(CreateSpaceModelLoaded(_space!));
final String? errorMessage = _checkDuplicateModelName(
event.allModels ?? [], event.spaceTemplate.modelName);
emit(CreateSpaceModelLoaded(_space!, errorMessage: errorMessage));
});
on<AddSubspacesToSpaceTemplate>((event, emit) {
final currentState = state;
if (currentState is CreateSpaceModelLoaded) {
final updatedSpace = currentState.space.copyWith(
subspaceModels: [
...(_space!.subspaceModels ?? []),
...event.subspaces,
],
);
emit(CreateSpaceModelLoaded(updatedSpace));
final eventSubspaceIds =
event.subspaces.map((e) => e.internalId).toSet();
// Update or retain subspaces
final updatedSubspaces = currentState.space.subspaceModels
?.where((subspace) =>
eventSubspaceIds.contains(subspace.internalId))
.map((subspace) {
final matchingEventSubspace = event.subspaces.firstWhere(
(e) => e.internalId == subspace.internalId,
orElse: () => subspace,
);
// Update the subspace's tags
final eventTagIds = matchingEventSubspace.tags
?.map((e) => e.internalId)
.toSet() ??
{};
final updatedTags = [
...?subspace.tags?.map<TagModel>((tag) {
final matchingTag =
matchingEventSubspace.tags?.firstWhere(
(e) => e.internalId == tag.internalId,
orElse: () => tag,
);
final isUpdated = matchingTag != tag;
return isUpdated
? tag.copyWith(tag: matchingTag?.tag)
: tag;
}) ??
<TagModel>[],
...?matchingEventSubspace.tags?.where(
(e) =>
subspace.tags
?.every((t) => t.internalId != e.internalId) ??
true,
) ??
<TagModel>[],
];
return subspace.copyWith(
subspaceName: matchingEventSubspace.subspaceName,
tags: updatedTags,
);
}).toList() ??
[];
// Add new subspaces
event.subspaces
.where((e) =>
updatedSubspaces.every((s) => s.internalId != e.internalId))
.forEach((newSubspace) {
updatedSubspaces.add(newSubspace);
});
final updatedSpace =
currentState.space.copyWith(subspaceModels: updatedSubspaces);
emit(CreateSpaceModelLoaded(updatedSpace,
errorMessage: currentState.errorMessage));
} else {
emit(CreateSpaceModelError("Space template not initialized"));
}
});
on<AddTagsToSpaceTemplate>((event, emit) {
final currentState = state;
if (currentState is CreateSpaceModelLoaded) {
final eventTagIds = event.tags.map((e) => e.internalId).toSet();
final updatedTags = currentState.space.tags
?.where((tag) => eventTagIds.contains(tag.internalId))
.map((tag) {
final matchingEventTag = event.tags.firstWhere(
(e) => e.internalId == tag.internalId,
orElse: () => tag,
);
return matchingEventTag != tag
? tag.copyWith(tag: matchingEventTag.tag)
: tag;
}).toList() ??
[];
event.tags
.where(
(e) => updatedTags.every((t) => t.internalId != e.internalId))
.forEach((e) {
updatedTags.add(e);
});
emit(CreateSpaceModelLoaded(
currentState.space.copyWith(tags: updatedTags)));
} else {
emit(CreateSpaceModelError("Space template not initialized"));
}
@ -87,8 +178,12 @@ class CreateSpaceModelBloc
on<UpdateSpaceTemplateName>((event, emit) {
final currentState = state;
if (currentState is CreateSpaceModelLoaded) {
if (event.name.trim().isEmpty) {
if (event.allModels.contains(event.name) == true) {
emit(CreateSpaceModelLoaded(
currentState.space,
errorMessage: "Duplicate Model name",
));
} else if (event.name.trim().isEmpty) {
emit(CreateSpaceModelLoaded(
currentState.space,
errorMessage: "Model name cannot be empty",
@ -96,12 +191,196 @@ class CreateSpaceModelBloc
} else {
final updatedSpaceModel =
currentState.space.copyWith(modelName: event.name);
emit(CreateSpaceModelLoaded(updatedSpaceModel));
}
} else {
emit(CreateSpaceModelError("Space template not initialized"));
}
});
on<ModifySpaceTemplate>((event, emit) async {
try {
if (event.spaceTemplate.uuid != null) {
final prevSpaceModel =
await _api.getSpaceModel(event.spaceTemplate.uuid ?? '');
final newSpaceModel = event.updatedSpaceTemplate;
String? spaceModelName;
if (prevSpaceModel?.modelName != newSpaceModel.modelName) {
spaceModelName = newSpaceModel.modelName;
}
List<TagModelUpdate> tagUpdates = [];
final List<UpdateSubspaceTemplateModel> subspaceUpdates = [];
final List<SubspaceTemplateModel>? prevSubspaces =
prevSpaceModel?.subspaceModels;
final List<SubspaceTemplateModel>? newSubspaces =
newSpaceModel.subspaceModels;
tagUpdates =
processTagUpdates(prevSpaceModel?.tags, newSpaceModel.tags);
if (prevSubspaces != null || newSubspaces != null) {
if (prevSubspaces != null && newSubspaces != null) {
for (var prevSubspace in prevSubspaces) {
final existsInNew = newSubspaces
.any((subspace) => subspace.uuid == prevSubspace.uuid);
if (!existsInNew) {
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.delete, uuid: prevSubspace.uuid));
}
}
} else if (prevSubspaces != null && newSubspaces == null) {
for (var prevSubspace in prevSubspaces) {
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.delete, uuid: prevSubspace.uuid));
}
}
if (newSubspaces != null) {
for (var newSubspace in newSubspaces!) {
// Tag without UUID
if ((newSubspace.uuid == null || newSubspace.uuid!.isEmpty)) {
final List<TagModelUpdate> tagUpdates = [];
if (newSubspace.tags != null) {
for (var tag in newSubspace.tags!) {
tagUpdates.add(TagModelUpdate(
action: Action.add,
uuid: tag.uuid == '' ? null : tag.uuid,
tag: tag.tag,
productUuid: tag.product?.uuid));
}
}
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.add,
subspaceName: newSubspace.subspaceName,
tags: tagUpdates));
}
}
}
if (prevSubspaces != null && newSubspaces != null) {
final newSubspaceMap = {
for (var subspace in newSubspaces!) subspace.uuid: subspace
};
for (var prevSubspace in prevSubspaces) {
final newSubspace = newSubspaceMap[prevSubspace.uuid];
if (newSubspace != null) {
final List<TagModelUpdate> tagSubspaceUpdates =
processTagUpdates(prevSubspace.tags, newSubspace.tags);
subspaceUpdates.add(UpdateSubspaceTemplateModel(
action: Action.update,
uuid: newSubspace.uuid,
subspaceName: newSubspace.subspaceName,
tags: tagSubspaceUpdates));
}
}
}
}
final spaceModelBody = CreateSpaceTemplateBodyModel(
modelName: spaceModelName,
tags: tagUpdates,
subspaceModels: subspaceUpdates);
final res = await _api.updateSpaceModel(
spaceModelBody, prevSpaceModel?.uuid ?? '');
if (res != null) {
emit(CreateSpaceModelLoaded(newSpaceModel));
if (event.onUpdate != null) {
event.onUpdate!(event.updatedSpaceTemplate);
}
}
}
} catch (e) {
emit(CreateSpaceModelError('Error creating space model'));
}
});
}
List<TagModelUpdate> processTagUpdates(
List<TagModel>? prevTags,
List<TagModel>? newTags,
) {
final List<TagModelUpdate> tagUpdates = [];
final processedTags = <String?>{};
if (prevTags == null && newTags != null) {
for (var newTag in newTags) {
tagUpdates.add(TagModelUpdate(
action: Action.add,
tag: newTag.tag,
uuid: newTag.uuid,
productUuid: newTag.product?.uuid,
));
}
return tagUpdates;
}
if (newTags != null || prevTags != null) {
// Case 1: Tags deleted
if (prevTags != null && newTags != null) {
for (var prevTag in prevTags) {
final existsInNew =
newTags!.any((newTag) => newTag.uuid == prevTag.uuid);
if (!existsInNew) {
tagUpdates
.add(TagModelUpdate(action: Action.delete, uuid: prevTag.uuid));
}
}
} else if (prevTags != null && newTags == null) {
for (var prevTag in prevTags) {
tagUpdates
.add(TagModelUpdate(action: Action.delete, uuid: prevTag.uuid));
}
}
// Case 2: Tags added
if (newTags != null) {
final prevTagUuids = prevTags?.map((t) => t.uuid).toSet() ?? {};
for (var newTag in newTags!) {
// Tag without UUID
if ((newTag.uuid == null || !prevTagUuids.contains(newTag.uuid)) &&
!processedTags.contains(newTag.tag)) {
tagUpdates.add(TagModelUpdate(
action: Action.add,
tag: newTag.tag,
uuid: newTag.uuid == '' ? null : newTag.uuid,
productUuid: newTag.product?.uuid));
processedTags.add(newTag.tag);
}
}
}
// Case 3: Tags updated
if (prevTags != null && newTags != null) {
final newTagMap = {for (var tag in newTags!) tag.uuid: tag};
for (var prevTag in prevTags!) {
final newTag = newTagMap[prevTag.uuid];
if (newTag != null) {
tagUpdates.add(TagModelUpdate(
action: Action.update,
uuid: newTag.uuid,
tag: newTag.tag,
));
} else {}
}
}
}
return tagUpdates;
}
String? _checkDuplicateModelName(List<String> allModels, String name) {
if (allModels.contains(name)) {
return "Duplicate Model name";
}
return null;
}
}

View File

@ -1,6 +1,7 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
abstract class CreateSpaceModelEvent extends Equatable {
const CreateSpaceModelEvent();
@ -13,8 +14,9 @@ class LoadSpaceTemplate extends CreateSpaceModelEvent {}
class UpdateSpaceTemplate extends CreateSpaceModelEvent {
final SpaceTemplateModel spaceTemplate;
List<String>? allModels;
UpdateSpaceTemplate(this.spaceTemplate);
UpdateSpaceTemplate(this.spaceTemplate,this.allModels);
}
class CreateSpaceTemplate extends CreateSpaceModelEvent {
@ -32,11 +34,12 @@ class CreateSpaceTemplate extends CreateSpaceModelEvent {
class UpdateSpaceTemplateName extends CreateSpaceModelEvent {
final String name;
final List<String> allModels;
UpdateSpaceTemplateName({required this.name});
UpdateSpaceTemplateName({required this.name, required this.allModels});
@override
List<Object> get props => [name];
List<Object> get props => [name, allModels];
}
class AddSubspacesToSpaceTemplate extends CreateSpaceModelEvent {
@ -45,8 +48,25 @@ class AddSubspacesToSpaceTemplate extends CreateSpaceModelEvent {
AddSubspacesToSpaceTemplate(this.subspaces);
}
class AddTagsToSpaceTemplate extends CreateSpaceModelEvent {
final List<TagModel> tags;
AddTagsToSpaceTemplate(this.tags);
}
class ValidateSpaceTemplateName extends CreateSpaceModelEvent {
final String name;
ValidateSpaceTemplateName({required this.name});
}
class ModifySpaceTemplate extends CreateSpaceModelEvent {
final SpaceTemplateModel spaceTemplate;
final SpaceTemplateModel updatedSpaceTemplate;
final Function(SpaceTemplateModel)? onUpdate;
ModifySpaceTemplate(
{required this.spaceTemplate,
required this.updatedSpaceTemplate,
this.onUpdate});
}

View File

@ -12,6 +12,7 @@ class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> {
required List<SpaceTemplateModel> initialSpaceModels,
}) : super(SpaceModelLoaded(spaceModels: initialSpaceModels)) {
on<CreateSpaceModel>(_onCreateSpaceModel);
on<UpdateSpaceModel>(_onUpdateSpaceModel);
}
Future<void> _onCreateSpaceModel(
@ -33,4 +34,23 @@ class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> {
}
}
}
Future<void> _onUpdateSpaceModel(
UpdateSpaceModel event, Emitter<SpaceModelState> emit) async {
final currentState = state;
if (currentState is SpaceModelLoaded) {
try {
final newSpaceModel =
await api.getSpaceModel(event.spaceModelUuid ?? '');
if (newSpaceModel != null) {
final updatedSpaceModels = currentState.spaceModels.map((model) {
return model.uuid == event.spaceModelUuid ? newSpaceModel : model;
}).toList();
emit(SpaceModelLoaded(spaceModels: updatedSpaceModels));
}
} catch (e) {
emit(SpaceModelError(message: e.toString()));
}
}
}
}

View File

@ -16,3 +16,21 @@ class CreateSpaceModel extends SpaceModelEvent {
@override
List<Object?> get props => [newSpaceModel];
}
class GetSpaceModel extends SpaceModelEvent {
final String spaceModelUuid;
GetSpaceModel({required this.spaceModelUuid});
@override
List<Object?> get props => [spaceModelUuid];
}
class UpdateSpaceModel extends SpaceModelEvent {
final String spaceModelUuid;
UpdateSpaceModel({required this.spaceModelUuid});
@override
List<Object?> get props => [spaceModelUuid];
}

View File

@ -1,5 +1,5 @@
class TagBodyModel {
late String uuid;
late String? uuid;
late String tag;
late final String? productUuid;
@ -30,12 +30,12 @@ class CreateSubspaceTemplateModel {
}
class CreateSpaceTemplateBodyModel {
final String modelName;
final String? modelName;
final List<dynamic>? tags;
final List<dynamic>? subspaceModels;
CreateSpaceTemplateBodyModel({
required this.modelName,
this.modelName,
this.tags,
this.subspaceModels,
});
@ -47,4 +47,9 @@ class CreateSpaceTemplateBodyModel {
'subspaceModels': subspaceModels,
};
}
@override
String toString() {
return toJson().toString();
}
}

View File

@ -1,7 +1,7 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';
import 'package:uuid/uuid.dart';
@ -13,7 +13,7 @@ class SpaceTemplateModel extends Equatable {
String internalId;
@override
List<Object?> get props => [modelName, subspaceModels];
List<Object?> get props => [modelName, subspaceModels, tags];
SpaceTemplateModel({
this.uuid,
@ -70,14 +70,14 @@ class SpaceTemplateModel extends Equatable {
}
class UpdateSubspaceTemplateModel {
final String uuid;
final String? uuid;
final Action action;
final String? subspaceName;
final List<UpdateTagModel>? tags;
final List<TagModelUpdate>? tags;
UpdateSubspaceTemplateModel({
required this.action,
required this.uuid,
this.uuid,
this.subspaceName,
this.tags,
});
@ -88,7 +88,7 @@ class UpdateSubspaceTemplateModel {
uuid: json['uuid'] ?? '',
subspaceName: json['subspaceName'] ?? '',
tags: (json['tags'] as List)
.map((item) => UpdateTagModel.fromJson(item))
.map((item) => TagModelUpdate.fromJson(item))
.toList(),
);
}
@ -103,44 +103,6 @@ class UpdateSubspaceTemplateModel {
}
}
class UpdateTagModel {
final Action action;
final String? uuid;
final String tag;
final bool disabled;
final ProductModel? product;
UpdateTagModel({
required this.action,
this.uuid,
required this.tag,
required this.disabled,
this.product,
});
factory UpdateTagModel.fromJson(Map<String, dynamic> json) {
return UpdateTagModel(
action: ActionExtension.fromValue(json['action']),
uuid: json['uuid'] ?? '',
tag: json['tag'] ?? '',
disabled: json['disabled'] ?? false,
product: json['product'] != null
? ProductModel.fromMap(json['product'])
: null,
);
}
Map<String, dynamic> toJson() {
return {
'action': action.value,
'uuid': uuid,
'tag': tag,
'disabled': disabled,
'product': product?.toMap(),
};
}
}
extension SpaceTemplateExtensions on SpaceTemplateModel {
List<String> listAllTagValues() {
final List<String> tagValues = [];

View File

@ -1,22 +1,28 @@
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:uuid/uuid.dart';
class SubspaceTemplateModel {
final String? uuid;
String subspaceName;
final bool disabled;
List<TagModel>? tags;
String internalId;
SubspaceTemplateModel({
this.uuid,
required this.subspaceName,
required this.disabled,
this.tags,
});
String? internalId,
}) : internalId = internalId ?? const Uuid().v4();
factory SubspaceTemplateModel.fromJson(Map<String, dynamic> json) {
final String internalId = json['internalId'] ?? const Uuid().v4();
return SubspaceTemplateModel(
uuid: json['uuid'] ?? '',
uuid: json['uuid'],
subspaceName: json['subspaceName'] ?? '',
internalId: internalId,
disabled: json['disabled'] ?? false,
tags: (json['tags'] as List<dynamic>?)
?.map((item) => TagModel.fromJson(item))
@ -33,4 +39,20 @@ class SubspaceTemplateModel {
'tags': tags?.map((e) => e.toJson()).toList() ?? [],
};
}
SubspaceTemplateModel copyWith({
String? uuid,
String? subspaceName,
bool? disabled,
List<TagModel>? tags,
String? internalId,
}) {
return SubspaceTemplateModel(
uuid: uuid ?? this.uuid,
subspaceName: subspaceName ?? this.subspaceName,
disabled: disabled ?? this.disabled,
tags: tags ?? this.tags,
internalId: internalId ?? this.internalId,
);
}
}

View File

@ -0,0 +1,16 @@
class CreateTagBodyModel {
late String tag;
late final String? productUuid;
Map<String, dynamic> toJson() {
return {
'tag': tag,
'productUuid': productUuid,
};
}
@override
String toString() {
return toJson().toString();
}
}

View File

@ -1,27 +1,27 @@
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/base_tag.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/create_space_template_body_model.dart';
import 'package:uuid/uuid.dart';
class TagModel {
String? uuid;
String? tag;
final ProductModel? product;
String internalId;
String? location;
TagModel(
{this.uuid,
required this.tag,
this.product,
String? internalId,
this.location})
: internalId = internalId ?? const Uuid().v4();
class TagModel extends BaseTag {
TagModel({
String? uuid,
required String? tag,
ProductModel? product,
String? internalId,
String? location,
}) : super(
uuid: uuid,
tag: tag,
product: product,
internalId: internalId,
location: location,
);
factory TagModel.fromJson(Map<String, dynamic> json) {
final String internalId = json['internalId'] ?? const Uuid().v4();
return TagModel(
uuid: json['uuid'] ?? '',
uuid: json['uuid'] ,
internalId: internalId,
tag: json['tag'] ?? '',
product: json['product'] != null
@ -30,15 +30,19 @@ class TagModel {
);
}
TagModel copyWith({
String? tag,
ProductModel? product,
String? location,
}) {
@override
TagModel copyWith(
{String? tag,
ProductModel? product,
String? uuid,
String? location,
String? internalId}) {
return TagModel(
tag: tag ?? this.tag,
product: product ?? this.product,
location: location ?? this.location,
internalId: internalId ?? this.internalId,
uuid:uuid?? this.uuid
);
}
@ -54,8 +58,8 @@ class TagModel {
extension TagModelExtensions on TagModel {
TagBodyModel toTagBodyModel() {
return TagBodyModel()
..uuid = uuid ?? ''
..uuid = uuid
..tag = tag ?? ''
..productUuid = product?.uuid;
}
}
}

View File

@ -0,0 +1,34 @@
import 'package:syncrow_web/utils/constants/action_enum.dart';
class TagModelUpdate {
final Action action;
final String? uuid;
final String? tag;
final String? productUuid;
TagModelUpdate({
required this.action,
this.uuid,
this.tag,
this.productUuid,
});
factory TagModelUpdate.fromJson(Map<String, dynamic> json) {
return TagModelUpdate(
action: json['action'],
uuid: json['uuid'],
tag: json['tag'],
productUuid: json['productUuid'],
);
}
// Method to convert an instance to JSON
Map<String, dynamic> toJson() {
return {
'action': action.value,
'uuid': uuid, // Nullable field
'tag': tag,
'productUuid': productUuid,
};
}
}

View File

@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/add_space_model_widget.dart';
@ -12,8 +11,10 @@ import 'package:syncrow_web/utils/color_manager.dart';
class SpaceModelPage extends StatelessWidget {
final List<ProductModel>? products;
final Function(List<SpaceTemplateModel>)? onSpaceModelsUpdated;
const SpaceModelPage({Key? key, this.products}) : super(key: key);
const SpaceModelPage({Key? key, this.products, this.onSpaceModelsUpdated})
: super(key: key);
@override
Widget build(BuildContext context) {
@ -24,6 +25,11 @@ class SpaceModelPage extends StatelessWidget {
} else if (state is SpaceModelLoaded) {
final spaceModels = state.spaceModels;
final allTagValues = _getAllTagValues(spaceModels);
final allSpaceModelNames = _getAllSpaceModelName(spaceModels);
if (onSpaceModelsUpdated != null) {
onSpaceModelsUpdated!(spaceModels);
}
return Scaffold(
backgroundColor: ColorsManager.whiteColors,
@ -52,12 +58,8 @@ class SpaceModelPage extends StatelessWidget {
return CreateSpaceModelDialog(
products: products,
allTags: allTagValues,
onLoad: (newModel) {
context.read<SpaceModelBloc>().add(
CreateSpaceModel(
newSpaceModel: newModel),
);
},
pageContext: context,
otherSpaceModels: allSpaceModelNames,
);
},
);
@ -67,10 +69,29 @@ class SpaceModelPage extends StatelessWidget {
}
// Render existing space model
final model = spaceModels[index];
return Container(
margin: const EdgeInsets.all(8.0),
child: SpaceModelCardWidget(model: model),
);
final otherModel =
List<String>.from(allSpaceModelNames);
otherModel.remove(model.modelName);
return GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return CreateSpaceModelDialog(
products: products,
allTags: allTagValues,
spaceModel: model,
otherSpaceModels: otherModel,
pageContext: context,
allSpaceModels: spaceModels,
);
},
);
},
child: Container(
margin: const EdgeInsets.all(8.0),
child: SpaceModelCardWidget(model: model),
));
},
),
),
@ -82,7 +103,10 @@ class SpaceModelPage extends StatelessWidget {
return Center(
child: Text(
'Error: ${state.message}',
style: const TextStyle(color: ColorsManager.warningRed),
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.warningRed),
),
);
}
@ -94,14 +118,14 @@ class SpaceModelPage extends StatelessWidget {
double _calculateChildAspectRatio(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
if (screenWidth > 1600) {
return 2; // Taller cards for larger screens
return 1.5; // Decrease to make cards taller
}
if (screenWidth > 1200) {
return 3; // Adjusted height for medium screens
return 2.0;
} else if (screenWidth > 800) {
return 3.5; // Adjusted height for smaller screens
return 2.5;
} else {
return 4.0; // Default ratio for smallest screens
return 3.0;
}
}
@ -114,4 +138,12 @@ class SpaceModelPage extends StatelessWidget {
}
return allTags;
}
List<String> _getAllSpaceModelName(List<SpaceTemplateModel> spaceModels) {
final List<String> names = [];
for (final spaceModel in spaceModels) {
names.add(spaceModel.modelName);
}
return names;
}
}

View File

@ -1,15 +1,15 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class ButtonContentWidget extends StatelessWidget {
final IconData icon;
final IconData? icon;
final String label;
final String? svgAssets;
const ButtonContentWidget({
Key? key,
required this.icon,
required this.label,
}) : super(key: key);
const ButtonContentWidget(
{Key? key, this.icon, required this.label, this.svgAssets})
: super(key: key);
@override
Widget build(BuildContext context) {
@ -30,10 +30,20 @@ class ButtonContentWidget extends StatelessWidget {
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0),
child: Row(
children: [
Icon(
icon,
color: ColorsManager.spaceColor,
),
if (icon != null)
Icon(
icon,
color: ColorsManager.spaceColor,
),
if (svgAssets != null)
Padding(
padding: const EdgeInsets.only(left: 6.0),
child: SvgPicture.asset(
svgAssets!,
width: screenWidth * 0.015, // Adjust icon size
height: screenWidth * 0.015,
),
),
const SizedBox(width: 10),
Expanded(
child: Text(

View File

@ -6,8 +6,11 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_mod
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/tag_chips_display_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_model_create_widget.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart';
@ -17,15 +20,19 @@ class CreateSpaceModelDialog extends StatelessWidget {
final List<ProductModel>? products;
final List<String>? allTags;
final SpaceTemplateModel? spaceModel;
final void Function(SpaceTemplateModel newModel)? onLoad;
final BuildContext? pageContext;
final List<String>? otherSpaceModels;
final List<SpaceTemplateModel>? allSpaceModels;
const CreateSpaceModelDialog({
Key? key,
this.products,
this.allTags,
this.spaceModel,
this.onLoad,
}) : super(key: key);
const CreateSpaceModelDialog(
{Key? key,
this.products,
this.allTags,
this.spaceModel,
this.pageContext,
this.otherSpaceModels,
this.allSpaceModels})
: super(key: key);
@override
Widget build(BuildContext context) {
@ -45,16 +52,20 @@ class CreateSpaceModelDialog extends StatelessWidget {
create: (_) {
final bloc = CreateSpaceModelBloc(_spaceModelApi);
if (spaceModel != null) {
bloc.add(UpdateSpaceTemplate(spaceModel!));
bloc.add(UpdateSpaceTemplate(spaceModel!, otherSpaceModels));
} else {
bloc.add(UpdateSpaceTemplate(SpaceTemplateModel(
modelName: '',
subspaceModels: const [],
)));
bloc.add(UpdateSpaceTemplate(
SpaceTemplateModel(
modelName: '',
subspaceModels: const [],
),
otherSpaceModels));
}
spaceNameController.addListener(() {
bloc.add(UpdateSpaceTemplateName(name: spaceNameController.text));
bloc.add(UpdateSpaceTemplateName(
name: spaceNameController.text,
allModels: otherSpaceModels ?? []));
});
return bloc;
@ -72,7 +83,9 @@ class CreateSpaceModelDialog extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Create New Space Model',
spaceModel?.uuid == null
? 'Create New Space Model'
: 'Edit Space Model',
style: Theme.of(context)
.textTheme
.headlineLarge
@ -84,18 +97,24 @@ class CreateSpaceModelDialog extends StatelessWidget {
child: TextField(
controller: spaceNameController,
onChanged: (value) {
context
.read<CreateSpaceModelBloc>()
.add(UpdateSpaceTemplateName(name: value));
context.read<CreateSpaceModelBloc>().add(
UpdateSpaceTemplateName(
name: value,
allModels: otherSpaceModels ?? []));
},
style: const TextStyle(color: ColorsManager.blackColor),
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: ColorsManager.blackColor),
decoration: InputDecoration(
filled: true,
fillColor: ColorsManager.textFieldGreyColor,
hintText: 'Please enter the name',
errorText: state.errorMessage,
hintStyle: const TextStyle(
color: ColorsManager.lightGrayColor),
hintStyle: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: ColorsManager.lightGrayColor),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide.none,
@ -108,21 +127,33 @@ class CreateSpaceModelDialog extends StatelessWidget {
),
),
const SizedBox(height: 16),
SubspaceModelCreate(context,
subspaces: state.space.subspaceModels ?? [],
allTags: allTags,
products: products,
spaceModel: spaceModel,
spaceTagModels: spaceModel?.tags ?? [],
spaceNameController: spaceNameController),
SubspaceModelCreate(
subspaces: state.space.subspaceModels ?? [],
tags: state.space.tags ?? [],
onSpaceModelUpdate: (updatedSubspaces,updatedTags) {
context
.read<CreateSpaceModelBloc>()
.add(AddSubspacesToSpaceTemplate(updatedSubspaces));
if(updatedTags!=null){
context
.read<CreateSpaceModelBloc>()
.add(AddTagsToSpaceTemplate(updatedTags));
}
},
),
const SizedBox(height: 10),
TagChipDisplay(context,
screenWidth: screenWidth,
spaceModel: updatedSpaceModel,
products: products,
subspaces: subspaces,
allTags: allTags,
spaceNameController: spaceNameController),
TagChipDisplay(
context,
screenWidth: screenWidth,
spaceModel: updatedSpaceModel,
products: products,
subspaces: subspaces,
allTags: allTags,
spaceNameController: spaceNameController,
pageContext: pageContext,
otherSpaceModels: otherSpaceModels,
allSpaceModels: allSpaceModels,
),
const SizedBox(height: 20),
SizedBox(
width: screenWidth * 0.25,
@ -131,38 +162,99 @@ class CreateSpaceModelDialog extends StatelessWidget {
Expanded(
child: CancelButton(
label: 'Cancel',
onPressed: () => Navigator.of(context).pop(),
onPressed: () {
Navigator.of(context).pop();
},
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
onPressed: state.errorMessage == null ||
isNameValid
? () {
onPressed: ((state.errorMessage != null &&
state.errorMessage != '') ||
!isNameValid)
? null
: () {
final updatedSpaceTemplate =
updatedSpaceModel.copyWith(
modelName:
spaceNameController.text.trim(),
);
context.read<CreateSpaceModelBloc>().add(
CreateSpaceTemplate(
spaceTemplate:
updatedSpaceTemplate,
onCreate: (newModel) {
onLoad!(newModel);
Navigator.of(context)
.pop(); // Close the dialog
},
),
);
}
: null,
if (updatedSpaceModel.uuid == null) {
context
.read<CreateSpaceModelBloc>()
.add(
CreateSpaceTemplate(
spaceTemplate:
updatedSpaceTemplate,
onCreate: (newModel) {
if (pageContext != null) {
pageContext!
.read<SpaceModelBloc>()
.add(CreateSpaceModel(
newSpaceModel:
newModel));
}
Navigator.of(context)
.pop(); // Close the dialog
},
),
);
} else {
if (pageContext != null) {
final currentState = pageContext!
.read<SpaceModelBloc>()
.state;
if (currentState
is SpaceModelLoaded) {
final spaceModels =
List<SpaceTemplateModel>.from(
currentState.spaceModels);
final SpaceTemplateModel?
currentSpaceModel = spaceModels
.cast<SpaceTemplateModel?>()
.firstWhere(
(sm) =>
sm?.uuid ==
updatedSpaceModel
.uuid,
orElse: () => null,
);
if (currentSpaceModel != null) {
context
.read<CreateSpaceModelBloc>()
.add(ModifySpaceTemplate(
spaceTemplate:
currentSpaceModel,
updatedSpaceTemplate:
updatedSpaceTemplate,
onUpdate: (newModel) {
if (pageContext !=
null) {
pageContext!
.read<
SpaceModelBloc>()
.add(UpdateSpaceModel(
spaceModelUuid:
newModel.uuid ??
''));
}
Navigator.of(context)
.pop();
}));
}
}
}
}
},
backgroundColor: ColorsManager.secondaryColor,
borderRadius: 10,
foregroundColor: isNameValid
? ColorsManager.whiteColors
: ColorsManager.whiteColorsWithOpacity,
foregroundColor: ((state.errorMessage != null &&
state.errorMessage != '') ||
!isNameValid)
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
child: const Text('OK'),
),
),
@ -174,7 +266,10 @@ class CreateSpaceModelDialog extends StatelessWidget {
} else if (state is CreateSpaceModelError) {
return Text(
'Error: ${state.message}',
style: const TextStyle(color: ColorsManager.warningRed),
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: ColorsManager.warningRed),
);
}

View File

@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/ellipsis_item_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/flexible_item_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class DynamicProductWidget extends StatelessWidget {
final Map<String, int> productTagCount;
final double maxWidth;
final double maxHeight;
const DynamicProductWidget({
Key? key,
required this.productTagCount,
required this.maxWidth,
required this.maxHeight,
}) : super(key: key);
@override
Widget build(BuildContext context) {
const double itemSpacing = 8.0;
const double lineSpacing = 8.0;
const double textPadding = 16.0;
const double itemHeight = 40.0;
List<Widget> productWidgets = [];
double currentLineWidth = 0.0;
double currentHeight = itemHeight;
for (final product in productTagCount.entries) {
final String prodType = product.key;
final int count = product.value;
final TextPainter textPainter = TextPainter(
text: TextSpan(
text: 'x$count',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
),
textDirection: TextDirection.ltr,
)..layout();
final double itemWidth = textPainter.width + textPadding + 20;
if (currentLineWidth + itemWidth + itemSpacing > maxWidth) {
currentHeight += itemHeight + lineSpacing;
if (currentHeight > maxHeight) {
productWidgets.add(const EllipsisItemWidget());
break;
}
currentLineWidth = 0.0;
}
productWidgets.add(FlexibleItemWidget(prodType: prodType, count: count));
currentLineWidth += itemWidth + itemSpacing;
}
return Wrap(
spacing: itemSpacing,
runSpacing: lineSpacing,
children: productWidgets,
);
}
}

View File

@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/room_name_widget.dart';
class DynamicRoomWidget extends StatelessWidget {
final List<SubspaceTemplateModel>? subspaceModels;
final double maxWidth;
final double maxHeight;
const DynamicRoomWidget({
Key? key,
required this.subspaceModels,
required this.maxWidth,
required this.maxHeight,
}) : super(key: key);
@override
Widget build(BuildContext context) {
const double itemSpacing = 8.0;
const double lineSpacing = 8.0;
const double textPadding = 16.0;
const double itemHeight = 30.0;
List<Widget> roomWidgets = [];
double currentLineWidth = 0.0;
double currentHeight = itemHeight;
for (final subspace in subspaceModels!) {
final TextPainter textPainter = TextPainter(
text: TextSpan(
text: subspace.subspaceName,
style: Theme.of(context).textTheme.bodyMedium
),
textDirection: TextDirection.ltr,
)..layout();
final double itemWidth = textPainter.width + textPadding;
if (currentLineWidth + itemWidth + itemSpacing > maxWidth) {
currentHeight += itemHeight + lineSpacing;
if (currentHeight > maxHeight) {
roomWidgets.add(const RoomNameWidget(name: "..."));
break;
}
currentLineWidth = 0.0;
}
roomWidgets.add(RoomNameWidget(name: subspace.subspaceName));
currentLineWidth += itemWidth + itemSpacing;
}
return Wrap(
spacing: itemSpacing,
runSpacing: lineSpacing,
children: roomWidgets,
);
}
}

View File

@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class EllipsisItemWidget extends StatelessWidget {
const EllipsisItemWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: ColorsManager.transparentColor),
),
child: Text(
"...",
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
),
);
}
}

View File

@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class FlexibleItemWidget extends StatelessWidget {
final String prodType;
final int count;
const FlexibleItemWidget({
Key? key,
required this.prodType,
required this.count,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: ColorsManager.transparentColor),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SvgPicture.asset(
prodType,
width: 15,
height: 16,
),
const SizedBox(width: 4),
Text(
'x$count',
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
),
],
),
);
}
}

View File

@ -0,0 +1,27 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class RoomNameWidget extends StatelessWidget {
final String name;
const RoomNameWidget({Key? key, required this.name}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: ColorsManager.transparentColor),
),
child: Text(
name,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
),
);
}
}

View File

@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_chip_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dynamic_product_widget.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dynamic_room_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class SpaceModelCardWidget extends StatelessWidget {
@ -31,112 +31,90 @@ class SpaceModelCardWidget extends StatelessWidget {
}
}
return Container(
decoration: BoxDecoration(
color: ColorsManager.whiteColors,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: ColorsManager.lightGrayColor.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: const Offset(0, 3),
return LayoutBuilder(
builder: (context, constraints) {
bool showOnlyName = constraints.maxWidth < 250;
return Container(
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: const Offset(0, 3),
),
],
),
],
),
padding: const EdgeInsets.fromLTRB(16.0, 14.0, 8.0, 8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: Text(
model.modelName,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
color: ColorsManager.blackColor,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(height: 10),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
model.modelName,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
color: Colors.black,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (!showOnlyName) ...[
const SizedBox(height: 10),
Expanded(
child: Wrap(
spacing: 3.0,
runSpacing: 3.0,
child: Row(
children: [
for (var subspace in model.subspaceModels!
.take(calculateTakeCount(context)))
SubspaceChipWidget(subspace: subspace.subspaceName),
// Left Container
Expanded(
flex: 1, // Distribute space proportionally
child: Container(
padding: const EdgeInsets.all(8.0),
child: LayoutBuilder(
builder: (context, constraints) {
return Align(
alignment: Alignment.topLeft,
child: DynamicRoomWidget(
subspaceModels: model.subspaceModels,
maxWidth: constraints.maxWidth,
maxHeight: constraints.maxHeight,
),
);
},
),
),
),
if (productTagCount.isNotEmpty &&
model.subspaceModels != null)
Container(
width: 1.0,
color: ColorsManager.softGray,
margin: const EdgeInsets.symmetric(vertical: 6.0),
),
Expanded(
flex: 1, // Distribute space proportionally
child: Container(
padding: const EdgeInsets.all(8.0),
child: LayoutBuilder(
builder: (context, constraints) {
return Align(
alignment: Alignment.topLeft,
child: DynamicProductWidget(
productTagCount: productTagCount,
maxWidth: constraints.maxWidth,
maxHeight: constraints.maxHeight));
},
),
),
),
],
),
),
if (productTagCount.isNotEmpty)
Container(
width: 1,
height: double.infinity,
color: ColorsManager.softGray,
margin: const EdgeInsets.symmetric(horizontal: 4.0),
),
const SizedBox(width: 7),
Expanded(
child: Wrap(
spacing: 4.0,
runSpacing: 4.0,
children: productTagCount.entries.map((entry) {
final prodType = entry.key;
final count = entry.value;
return Chip(
label: Row(
mainAxisSize: MainAxisSize.min,
children: [
SvgPicture.asset(
prodType,
width: 15,
height: 16,
),
const SizedBox(width: 4),
Text(
'x$count', // Product count
style: const TextStyle(fontSize: 12),
),
],
),
backgroundColor: ColorsManager.textFieldGreyColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(
color: ColorsManager.transparentColor,
width: 0,
),
),
);
}).toList(),
),
),
],
),
]
],
),
const SizedBox(height: 5),
],
),
);
},
);
}
int calculateTakeCount(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
// Adjust the count based on the screen width
if (screenWidth > 1500) {
return 3; // For large screens
} else if (screenWidth > 1200) {
return 2;
} else {
return 1; // For smaller screens
}
}
}

View File

@ -11,24 +11,25 @@ class SubspaceChipWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Chip(
label: Text(
subspace,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
backgroundColor: ColorsManager.textFieldGreyColor,
labelStyle: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
shape: RoundedRectangleBorder(
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(8),
side: const BorderSide(
border: Border.all(
color: ColorsManager.transparentColor,
width: 0,
),
),
child: Text(
subspace,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
),
);
}
}

View File

@ -1,61 +1,53 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/common/edit_chip.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/views/create_subspace_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/subspace_name_label_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class SubspaceModelCreate extends StatelessWidget {
class SubspaceModelCreate extends StatefulWidget {
final List<SubspaceTemplateModel> subspaces;
final TextEditingController spaceNameController;
final List<TagModel>? spaceTagModels;
final List<String>? allTags;
final List<ProductModel>? products;
final SpaceTemplateModel? spaceModel;
final void Function(
List<SubspaceTemplateModel> newSubspaces, List<TagModel>? tags)?
onSpaceModelUpdate;
final List<TagModel> tags;
const SubspaceModelCreate(
BuildContext context, {
const SubspaceModelCreate({
Key? key,
required this.subspaces,
this.spaceTagModels,
required this.allTags,
required this.products,
required this.spaceModel,
required this.spaceNameController,
this.onSpaceModelUpdate,
required this.tags,
}) : super(key: key);
@override
_SubspaceModelCreateState createState() => _SubspaceModelCreateState();
}
class _SubspaceModelCreateState extends State<SubspaceModelCreate> {
late List<SubspaceTemplateModel> _subspaces;
String? errorSubspaceId;
late List<TagModel> _tags;
@override
void initState() {
super.initState();
_subspaces = List.from(widget.subspaces);
_tags = List.from(widget.tags);
}
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return Container(
child: subspaces.isEmpty
child: _subspaces.isEmpty
? TextButton(
style: TextButton.styleFrom(
overlayColor: ColorsManager.transparentColor,
),
onPressed: () async {
Navigator.of(context).pop();
await showDialog<List<SubspaceTemplateModel>>(
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return CreateSubSpaceModelDialog(
allTags: allTags,
spaceName: spaceNameController.text,
spaceModel: spaceModel,
spaceTagModels: spaceTagModels,
products: products,
isEdit: true,
dialogTitle: subspaces.isEmpty
? 'Create Sub-space'
: 'Edit Sub-space',
existingSubSpaces: subspaces,
);
},
);
await _openDialog(context, 'Create Sub-space');
},
child: const ButtonContentWidget(
icon: Icons.add,
@ -71,64 +63,37 @@ class SubspaceModelCreate extends StatelessWidget {
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: ColorsManager.textFieldGreyColor,
width: 3.0, // Border width
width: 3.0,
),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
...subspaces.map(
(subspace) => Chip(
label: Text(
subspace.subspaceName,
style: const TextStyle(
color: ColorsManager.spaceColor), // Text color
),
backgroundColor: ColorsManager.whiteColors, // Chip background color
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(16), // Rounded chip
side: const BorderSide(
color: ColorsManager.spaceColor), // Border color
),
),
),
GestureDetector(
..._subspaces.map((subspace) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SubspaceNameDisplayWidget(
text: subspace.subspaceName,
validateName: (updatedName) {
return !_subspaces.any((s) =>
s != subspace &&
s.subspaceName == updatedName);
},
onNameChanged: (updatedName) {
setState(() {
subspace.subspaceName = updatedName;
});
},
),
],
);
}),
EditChip(
onTap: () async {
Navigator.of(context).pop();
await showDialog<List<SubspaceTemplateModel>>(
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return CreateSubSpaceModelDialog(
isEdit: true,
dialogTitle: 'Edit Sub-space',
existingSubSpaces: subspaces,
allTags: allTags,
spaceName: spaceNameController.text,
spaceTagModels: spaceTagModels,
products: products,
spaceModel: spaceModel,
);
},
);
await _openDialog(context, 'Edit Sub-space');
},
child: Chip(
label: const Text(
'Edit',
style: TextStyle(
color: ColorsManager.spaceColor),
),
backgroundColor:
ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(16),
side: const BorderSide(
color: ColorsManager.spaceColor),
),
),
),
],
),
@ -136,4 +101,40 @@ class SubspaceModelCreate extends StatelessWidget {
),
);
}
Future<void> _openDialog(BuildContext context, String dialogTitle) async {
await showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return CreateSubSpaceModelDialog(
isEdit: true,
dialogTitle: dialogTitle,
existingSubSpaces: _subspaces,
onUpdate: (subspaceModels) {
final updatedIds = subspaceModels.map((s) => s.internalId).toSet();
final deletedSubspaces = _subspaces
.where((s) => !updatedIds.contains(s.internalId))
.toList();
final List<TagModel> tagsToAppendToSpace = [];
for (var s in deletedSubspaces) {
if (s.tags != null) {
tagsToAppendToSpace.addAll(s.tags!);
}
}
setState(() {
_subspaces = subspaceModels;
_tags.addAll(tagsToAppendToSpace);
});
if (widget.onSpaceModelUpdate != null) {
widget.onSpaceModelUpdate!(subspaceModels, _tags);
}
},
);
},
);
}
}

View File

@ -0,0 +1,137 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class SubspaceNameDisplayWidget extends StatefulWidget {
final String text;
final TextStyle? textStyle;
final Color backgroundColor;
final Color borderColor;
final EdgeInsetsGeometry padding;
final BorderRadiusGeometry borderRadius;
final void Function(String updatedName) onNameChanged;
final bool Function(String updatedName) validateName;
const SubspaceNameDisplayWidget({
Key? key,
required this.text,
this.textStyle,
this.backgroundColor = ColorsManager.whiteColors,
this.borderColor = ColorsManager.transparentColor,
this.padding = const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
this.borderRadius = const BorderRadius.all(Radius.circular(10)),
required this.onNameChanged,
required this.validateName,
}) : super(key: key);
@override
_SubspaceNameDisplayWidgetState createState() =>
_SubspaceNameDisplayWidgetState();
}
class _SubspaceNameDisplayWidgetState extends State<SubspaceNameDisplayWidget> {
bool isEditing = false;
late TextEditingController _controller;
late FocusNode _focusNode;
late String previousName;
String? errorText;
@override
void initState() {
super.initState();
_controller = TextEditingController(text: widget.text);
_focusNode = FocusNode();
previousName = widget.text;
}
@override
void dispose() {
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
void _handleValidationAndSave() {
final updatedName = _controller.text;
if (updatedName.isEmpty) {
setState(() {
errorText = 'Subspace name cannot be empty.';
});
return;
}
if (widget.validateName(updatedName)) {
setState(() {
errorText = null;
isEditing = false;
previousName = updatedName;
widget.onNameChanged(updatedName);
});
} else {
setState(() {
errorText = 'Subspace name already exists.';
});
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () {
setState(() {
isEditing = true;
_focusNode.requestFocus();
});
},
child: Container(
padding: widget.padding,
decoration: BoxDecoration(
color: widget.backgroundColor,
borderRadius: widget.borderRadius,
border: Border.all(color: widget.borderColor),
),
child: isEditing
? TextField(
controller: _controller,
focusNode: _focusNode,
style: widget.textStyle ??
Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
autofocus: true,
decoration: const InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(horizontal: 8.0),
),
onSubmitted: (value) {
_handleValidationAndSave();
},
)
: Text(
widget.text,
style: widget.textStyle ??
Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: ColorsManager.spaceColor),
),
),
),
if (errorText != null)
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(
errorText!,
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: ColorsManager.warningRed),
),
),
],
);
}
}

View File

@ -1,10 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/common/edit_chip.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
@ -16,17 +17,22 @@ class TagChipDisplay extends StatelessWidget {
final List<SubspaceTemplateModel>? subspaces;
final List<String>? allTags;
final TextEditingController spaceNameController;
final BuildContext? pageContext;
final List<String>? otherSpaceModels;
final List<SpaceTemplateModel>? allSpaceModels;
const TagChipDisplay(
BuildContext context, {
Key? key,
required this.screenWidth,
required this.spaceModel,
required this.products,
required this.subspaces,
required this.allTags,
required this.spaceNameController,
}) : super(key: key);
const TagChipDisplay(BuildContext context,
{Key? key,
required this.screenWidth,
required this.spaceModel,
required this.products,
required this.subspaces,
required this.allTags,
required this.spaceNameController,
this.pageContext,
this.otherSpaceModels,
this.allSpaceModels})
: super(key: key);
@override
Widget build(BuildContext context) {
@ -51,7 +57,7 @@ class TagChipDisplay extends StatelessWidget {
runSpacing: 8.0,
children: [
// Combine tags from spaceModel and subspaces
..._groupTags([
...TagHelper.groupTags([
...?spaceModel?.tags,
...?spaceModel?.subspaceModels
?.expand((subspace) => subspace.tags ?? [])
@ -67,9 +73,12 @@ class TagChipDisplay extends StatelessWidget {
),
label: Text(
'x${entry.value}', // Show count
style: const TextStyle(
color: ColorsManager.spaceColor,
),
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(
color:
ColorsManager.spaceColor),
),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
@ -80,41 +89,31 @@ class TagChipDisplay extends StatelessWidget {
),
),
),
GestureDetector(
onTap: () async {
Navigator.of(context).pop();
EditChip(onTap: () async {
// Use the Navigator's context for showDialog
Navigator.of(context).pop();
await showDialog<bool>(
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (context) => AddDeviceTypeModelWidget(
products: products,
subspaces: subspaces,
allTags: allTags,
spaceName: spaceNameController.text,
spaceTagModels: spaceModel?.tags,
initialSelectedProducts:
_createInitialSelectedProducts(
spaceModel?.tags, spaceModel?.subspaceModels),
),
);
// Edit action
},
child: Chip(
label: const Text(
'Edit',
style: TextStyle(
color: ColorsManager.spaceColor),
),
backgroundColor:
ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(
color: ColorsManager.spaceColor),
),
),
),
builder: (context) => AssignTagModelsDialog(
products: products,
allSpaceModels: allSpaceModels,
subspaces: subspaces,
pageContext: pageContext,
allTags: allTags,
spaceModel: spaceModel,
otherSpaceModels: otherSpaceModels,
initialTags: TagHelper.generateInitialTags(
subspaces: subspaces,
spaceTagModels: spaceModel?.tags ?? []),
title: 'Edit Device',
addedProducts:
TagHelper.createInitialSelectedProducts(
spaceModel?.tags ?? [], subspaces),
spaceName: spaceModel?.modelName ?? '',
));
})
],
),
),
@ -123,7 +122,7 @@ class TagChipDisplay extends StatelessWidget {
onPressed: () async {
Navigator.of(context).pop();
final result = await showDialog<bool>(
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (context) => AddDeviceTypeModelWidget(
@ -131,9 +130,12 @@ class TagChipDisplay extends StatelessWidget {
subspaces: subspaces,
allTags: allTags,
spaceName: spaceNameController.text,
pageContext: pageContext,
isCreate: true,
spaceModel: spaceModel,
otherSpaceModels: otherSpaceModels,
),
);
if (result == true) {}
},
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
@ -144,49 +146,4 @@ class TagChipDisplay extends StatelessWidget {
),
);
}
Map<ProductModel, int> _groupTags(List<TagModel> tags) {
final Map<ProductModel, int> groupedTags = {};
for (var tag in tags) {
if (tag.product != null) {
groupedTags[tag.product!] = (groupedTags[tag.product!] ?? 0) + 1;
}
}
return groupedTags;
}
List<SelectedProduct> _createInitialSelectedProducts(
List<TagModel>? tags, List<SubspaceTemplateModel>? subspaces) {
final Map<ProductModel, int> productCounts = {};
if (tags != null) {
for (var tag in tags) {
if (tag.product != null) {
productCounts[tag.product!] = (productCounts[tag.product!] ?? 0) + 1;
}
}
}
if (subspaces != null) {
for (var subspace in subspaces) {
if (subspace.tags != null) {
for (var tag in subspace.tags!) {
if (tag.product != null) {
productCounts[tag.product!] =
(productCounts[tag.product!] ?? 0) + 1;
}
}
}
}
}
return productCounts.entries
.map((entry) => SelectedProduct(
productId: entry.key.uuid,
count: entry.value,
productName: entry.key.name ?? 'Unnamed',
product: entry.key,
))
.toList();
}
}

View File

@ -1,38 +1,75 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart';
class AddDeviceTypeModelBloc
extends Bloc<AddDeviceTypeModelEvent, List<SelectedProduct>> {
AddDeviceTypeModelBloc(List<SelectedProduct> initialProducts)
: super(initialProducts) {
extends Bloc<AddDeviceTypeModelEvent, AddDeviceModelState> {
AddDeviceTypeModelBloc() : super(AddDeviceModelInitial()) {
on<InitializeDeviceTypeModel>(_onInitializeTagModels);
on<UpdateProductCountEvent>(_onUpdateProductCount);
}
void _onUpdateProductCount(
UpdateProductCountEvent event, Emitter<List<SelectedProduct>> emit) {
final existingProduct = state.firstWhere(
(p) => p.productId == event.productId,
orElse: () => SelectedProduct(productId: event.productId, count: 0,productName: event.productName,product: event.product ),
);
void _onInitializeTagModels(
InitializeDeviceTypeModel event, Emitter<AddDeviceModelState> emit) {
emit(AddDeviceModelLoaded(
selectedProducts: event.addedProducts,
initialTag: event.initialTags,
));
}
if (event.count > 0) {
if (!state.contains(existingProduct)) {
emit([
...state,
SelectedProduct(productId: event.productId, count: event.count, productName: event.productName, product: event.product)
]);
void _onUpdateProductCount(
UpdateProductCountEvent event, Emitter<AddDeviceModelState> emit) {
final currentState = state;
if (currentState is AddDeviceModelLoaded) {
final existingProduct = currentState.selectedProducts.firstWhere(
(p) => p.productId == event.productId,
orElse: () => SelectedProduct(
productId: event.productId,
count: 0,
productName: event.productName,
product: event.product,
),
);
List<SelectedProduct> updatedProducts;
if (event.count > 0) {
if (!currentState.selectedProducts.contains(existingProduct)) {
updatedProducts = [
...currentState.selectedProducts,
SelectedProduct(
productId: event.productId,
count: event.count,
productName: event.productName,
product: event.product,
),
];
} else {
updatedProducts = currentState.selectedProducts.map((p) {
if (p.productId == event.productId) {
return SelectedProduct(
productId: p.productId,
count: event.count,
productName: p.productName,
product: p.product,
);
}
return p;
}).toList();
}
} else {
final updatedList = state.map((p) {
if (p.productId == event.productId) {
return SelectedProduct(productId: p.productId, count: event.count, productName: p.productName,product: p.product);
}
return p;
}).toList();
emit(updatedList);
// Remove the product if the count is 0
updatedProducts = currentState.selectedProducts
.where((p) => p.productId != event.productId)
.toList();
}
} else {
emit(state.where((p) => p.productId != event.productId).toList());
// Emit the updated state
emit(AddDeviceModelLoaded(
selectedProducts: updatedProducts,
initialTag: currentState.initialTag));
}
}
}

View File

@ -0,0 +1,36 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
abstract class AddDeviceModelState extends Equatable {
const AddDeviceModelState();
@override
List<Object> get props => [];
}
class AddDeviceModelInitial extends AddDeviceModelState {}
class AddDeviceModelLoading extends AddDeviceModelState {}
class AddDeviceModelLoaded extends AddDeviceModelState {
final List<SelectedProduct> selectedProducts;
final List<TagModel> initialTag;
const AddDeviceModelLoaded({
required this.selectedProducts,
required this.initialTag,
});
@override
List<Object> get props => [selectedProducts, initialTag];
}
class AddDeviceModelError extends AddDeviceModelState {
final String errorMessage;
const AddDeviceModelError(this.errorMessage);
@override
List<Object> get props => [errorMessage];
}

View File

@ -1,11 +1,16 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
abstract class AddDeviceTypeModelEvent extends Equatable {
const AddDeviceTypeModelEvent();
@override
List<Object> get props => [];
}
class UpdateProductCountEvent extends AddDeviceTypeModelEvent {
final String productId;
final int count;
@ -17,3 +22,17 @@ class UpdateProductCountEvent extends AddDeviceTypeModelEvent {
@override
List<Object> get props => [productId, count];
}
class InitializeDeviceTypeModel extends AddDeviceTypeModelEvent {
final List<TagModel> initialTags;
final List<SelectedProduct> addedProducts;
const InitializeDeviceTypeModel({
this.initialTags = const [],
required this.addedProducts,
});
@override
List<Object> get props => [initialTags, addedProducts];
}

View File

@ -1,36 +1,47 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/assign_tag_models/views/assign_tag_models_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/create_space_model_dialog.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/widgets/action_button_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/widgets/scrollable_grid_view_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class AddDeviceTypeModelWidget extends StatelessWidget {
final List<ProductModel>? products;
final ValueChanged<List<SelectedProduct>>? onProductsSelected;
final List<SelectedProduct>? initialSelectedProducts;
final List<SubspaceTemplateModel>? subspaces;
final List<TagModel>? spaceTagModels;
final List<String>? allTags;
final String spaceName;
final bool isCreate;
final List<String>? otherSpaceModels;
final BuildContext? pageContext;
final SpaceTemplateModel? spaceModel;
final List<SpaceTemplateModel>? allSpaceModels;
const AddDeviceTypeModelWidget(
{super.key,
this.products,
this.initialSelectedProducts,
this.onProductsSelected,
this.subspaces,
this.allTags,
this.spaceTagModels,
required this.spaceName});
required this.spaceName,
required this.isCreate,
this.pageContext,
this.otherSpaceModels,
this.spaceModel,
this.allSpaceModels});
@override
Widget build(BuildContext context) {
@ -42,115 +53,157 @@ class AddDeviceTypeModelWidget extends StatelessWidget {
: 3;
return BlocProvider(
create: (_) => AddDeviceTypeModelBloc(initialSelectedProducts ?? []),
child: Builder(
builder: (context) => AlertDialog(
title: const Text('Add Devices'),
backgroundColor: ColorsManager.whiteColors,
content: SingleChildScrollView(
child: Container(
width: size.width * 0.9,
height: size.height * 0.65,
color: ColorsManager.textFieldGreyColor,
child: Column(
children: [
const SizedBox(height: 16),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: ScrollableGridViewWidget(
products: products, crossAxisCount: crossAxisCount),
),
create: (_) => AddDeviceTypeModelBloc()
..add(InitializeDeviceTypeModel(
initialTags: spaceTagModels ?? [],
addedProducts: initialSelectedProducts ?? [],
)),
child: Builder(
builder: (context) => AlertDialog(
title: const Text('Add Devices'),
backgroundColor: ColorsManager.whiteColors,
content: BlocBuilder<AddDeviceTypeModelBloc, AddDeviceModelState>(
builder: (context, state) {
if (state is AddDeviceModelLoading) {
return const Center(child: CircularProgressIndicator());
}
if (state is AddDeviceModelLoaded) {
return SingleChildScrollView(
child: Container(
width: size.width * 0.9,
height: size.height * 0.65,
color: ColorsManager.textFieldGreyColor,
child: Column(
children: [
const SizedBox(height: 16),
Expanded(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20.0),
child: ScrollableGridViewWidget(
isCreate: isCreate,
products: products,
crossAxisCount: crossAxisCount,
initialProductCounts: state.selectedProducts,
),
),
),
],
),
],
),
),
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CancelButton(
label: 'Cancel',
onPressed: () async {
),
);
}
return const SizedBox();
},
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CancelButton(
label: 'Cancel',
onPressed: () async {
if (isCreate) {
Navigator.of(context).pop();
await showDialog(
barrierDismissible: false,
context: context,
builder: (context) => CreateSpaceModelDialog(
builder: (BuildContext dialogContext) {
return CreateSpaceModelDialog(
allSpaceModels: allSpaceModels,
products: products,
allTags: allTags,
pageContext: pageContext,
otherSpaceModels: otherSpaceModels,
spaceModel: SpaceTemplateModel(
modelName: spaceName,
subspaceModels: subspaces,
tags: spaceTagModels,
)),
modelName: spaceName,
tags: spaceModel?.tags ?? [],
uuid: spaceModel?.uuid,
internalId: spaceModel?.internalId,
subspaceModels: subspaces),
);
},
);
} else {
final initialTags = TagHelper.generateInitialTags(
spaceTagModels: spaceTagModels,
subspaces: subspaces,
);
Navigator.of(context).pop();
await showDialog<bool>(
context: context,
builder: (context) => AssignTagModelsDialog(
products: products,
subspaces: subspaces,
addedProducts: initialSelectedProducts ?? [],
allTags: allTags,
spaceName: spaceName,
initialTags: initialTags,
otherSpaceModels: otherSpaceModels,
title: 'Edit Device',
spaceModel: spaceModel,
pageContext: pageContext,
));
}
},
),
SizedBox(
width: 140,
child:
BlocBuilder<AddDeviceTypeModelBloc, AddDeviceModelState>(
builder: (context, state) {
final isDisabled = state is AddDeviceModelLoaded &&
state.selectedProducts.isEmpty;
return DefaultButton(
backgroundColor: ColorsManager.secondaryColor,
foregroundColor: isDisabled
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
borderRadius: 10,
onPressed: isDisabled
? null // Disable the button
: () async {
if (state is AddDeviceModelLoaded &&
state.selectedProducts.isNotEmpty) {
final initialTags =
TagHelper.generateInitialTags(
spaceTagModels: spaceTagModels,
subspaces: subspaces,
);
final dialogTitle = initialTags.isNotEmpty
? 'Edit Device'
: 'Assign Tags';
Navigator.of(context).pop();
await showDialog<bool>(
context: context,
builder: (context) => AssignTagModelsDialog(
products: products,
allSpaceModels: allSpaceModels,
subspaces: subspaces,
addedProducts: state.selectedProducts,
allTags: allTags,
spaceName: spaceName,
initialTags: initialTags,
otherSpaceModels: otherSpaceModels,
title: dialogTitle,
spaceModel: spaceModel,
pageContext: pageContext,
),
);
}
},
child: const Text('Next'),
);
},
),
ActionButton(
label: 'Continue',
backgroundColor: ColorsManager.secondaryColor,
foregroundColor: ColorsManager.whiteColors,
onPressed: () async {
final currentState =
context.read<AddDeviceTypeModelBloc>().state;
Navigator.of(context).pop();
if (currentState.isNotEmpty) {
final initialTags = generateInitialTags(
spaceTagModels: spaceTagModels,
subspaces: subspaces,
);
final dialogTitle = initialTags.isNotEmpty
? 'Edit Device'
: 'Assign Tags';
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (context) => AssignTagModelsDialog(
products: products,
subspaces: subspaces,
addedProducts: currentState,
allTags: allTags,
spaceName: spaceName,
initialTags: initialTags,
title: dialogTitle,
),
);
}
},
),
],
),
],
),
));
}
List<TagModel> generateInitialTags({
List<TagModel>? spaceTagModels,
List<SubspaceTemplateModel>? subspaces,
}) {
final List<TagModel> initialTags = [];
if (spaceTagModels != null) {
initialTags.addAll(spaceTagModels);
}
if (subspaces != null) {
for (var subspace in subspaces) {
if (subspace.tags != null) {
initialTags.addAll(
subspace.tags!.map(
(tag) => tag.copyWith(location: subspace.subspaceName),
),
],
),
);
}
}
}
return initialTags;
],
),
),
);
}
}

View File

@ -13,12 +13,13 @@ import 'package:syncrow_web/utils/constants/assets.dart';
class DeviceTypeTileWidget extends StatelessWidget {
final ProductModel product;
final List<SelectedProduct> productCounts;
final bool isCreate;
const DeviceTypeTileWidget({
super.key,
required this.product,
required this.productCounts,
});
const DeviceTypeTileWidget(
{super.key,
required this.product,
required this.productCounts,
required this.isCreate});
@override
Widget build(BuildContext context) {
@ -48,6 +49,7 @@ class DeviceTypeTileWidget extends StatelessWidget {
DeviceNameWidget(name: product.name),
const SizedBox(height: 4),
CounterWidget(
isCreate: isCreate,
initialCount: selectedProduct.count,
onCountChanged: (newCount) {
context.read<AddDeviceTypeModelBloc>().add(

Some files were not shown because too many files have changed in this diff Show More