1818use Sylius \Component \Resource \Factory \FactoryInterface ;
1919use Sylius \Component \Resource \Repository \RepositoryInterface ;
2020use Sylius \InvoicingPlugin \Entity \InvoiceSequenceInterface ;
21+ use Sylius \InvoicingPlugin \Enum \InvoiceSequenceScopeEnum ;
2122use Symfony \Component \Clock \ClockInterface ;
2223
2324final class SequentialInvoiceNumberGenerator implements InvoiceNumberGenerator
@@ -29,7 +30,17 @@ public function __construct(
2930 private readonly ClockInterface $ clock ,
3031 private readonly int $ startNumber = 1 ,
3132 private readonly int $ numberLength = 9 ,
33+ private readonly ?string $ scope = null ,
3234 ) {
35+ if (null === $ this ->scope ) {
36+ trigger_deprecation (
37+ 'sylius/invoicing-plugin ' ,
38+ '2.1 ' ,
39+ 'Not passing a "%s" to "%s" is deprecated and will be required in SyliusInvoicingPlugin 3.0. ' ,
40+ InvoiceSequenceScopeEnum::class,
41+ self ::class,
42+ );
43+ }
3344 }
3445
3546 public function generate (): string
@@ -56,15 +67,38 @@ private function generateNumber(int $index): string
5667
5768 private function getSequence (): InvoiceSequenceInterface
5869 {
59- /** @var InvoiceSequenceInterface $sequence */
60- $ sequence = $ this ->sequenceRepository ->findOneBy ([]);
61-
62- if (null != $ sequence ) {
70+ $ now = $ this ->clock ->now ();
71+ $ scope = InvoiceSequenceScopeEnum::tryFrom ($ this ->scope ?? '' ) ?? InvoiceSequenceScopeEnum::GLOBAL ;
72+
73+ $ criteria = match ($ scope ) {
74+ InvoiceSequenceScopeEnum::MONTHLY => [
75+ 'year ' => (int ) $ now ->format ('Y ' ),
76+ 'month ' => (int ) $ now ->format ('m ' ),
77+ ],
78+ InvoiceSequenceScopeEnum::ANNUALLY => [
79+ 'year ' => (int ) $ now ->format ('Y ' ),
80+ ],
81+ InvoiceSequenceScopeEnum::GLOBAL => [],
82+ };
83+
84+ /** @var InvoiceSequenceInterface|null $sequence */
85+ $ sequence = $ this ->sequenceRepository ->findOneBy ($ criteria );
86+
87+ if (null !== $ sequence ) {
6388 return $ sequence ;
6489 }
6590
6691 /** @var InvoiceSequenceInterface $sequence */
6792 $ sequence = $ this ->sequenceFactory ->createNew ();
93+
94+ if (isset ($ criteria ['year ' ])) {
95+ $ sequence ->setYear ($ criteria ['year ' ]);
96+ }
97+
98+ if (isset ($ criteria ['month ' ])) {
99+ $ sequence ->setMonth ($ criteria ['month ' ]);
100+ }
101+
68102 $ this ->sequenceManager ->persist ($ sequence );
69103
70104 return $ sequence ;
0 commit comments