This paper proposes an integrated approach to optimize energy systems for urban energy communities by considering both energy generation and demand, using a mixed-integer linear programming method. The study finds that allowing flexibility in electricity demand can reduce system costs and CO2 emissions significantly, particularly when users with matching renewable energy generation profiles are aggregated. The results highlight the importance of including various user types and their energy needs in the design and operation optimization of energy communities.