Changes between Initial Version and Version 1 of Transactions


Ignore:
Timestamp:
09/01/25 05:32:06 (31 hours ago)
Author:
222003
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Transactions

    v1 v1  
     1== Трансакции ==
     2
     3=== 1. Транзакција за креирање на нарачка од страна на Клиент ===
     4
     5{{{
     6 @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED, timeout = 30)
     7    public Clientorder checkout(Client client, Shoppingcart cart, Integer paymentMethodId, Integer deliveryCompanyId, boolean useCard) {
     8        BigDecimal total = shoppingCartService.getTotal(cart);
     9
     10        int baseAmount = total.intValue();
     11        int discount = 0;
     12        if (useCard) {
     13            var cardOpt = clubCardService.getByClientId(client.getId());
     14            if (cardOpt.isPresent()) {
     15                Clubcard card = cardOpt.get();
     16                Integer pts = card.getPoints();
     17                int points = pts == null ? 0 : pts;
     18                discount = Math.min(points / 2, baseAmount);
     19                if (discount > 0) {
     20                    card.setPoints(0);
     21                }
     22            }
     23        }
     24        int finalAmount = Math.max(0, baseAmount - discount);
     25
     26        Paymentmethod method = paymentmethodRepo.findById(paymentMethodId)
     27                .orElseThrow(() -> new IllegalArgumentException("Payment method not found"));
     28
     29        Payment payment = new Payment();
     30        payment.setClient(client);
     31        payment.setPaymentMethod(method);
     32        payment.setPaymentDate(LocalDate.now());
     33        payment.setAmount(finalAmount);
     34        //payment.setStatus("во тек");
     35        paymentRepo.save(payment);
     36
     37        Deliverycompany deliveryCompany = deliveryRepo.findById(deliveryCompanyId)
     38                .orElseThrow(() -> new IllegalArgumentException("Delivery company not found"));
     39
     40        Clientorder order = new Clientorder();
     41        order.setClient(client);
     42        order.setDeliveryCompany(deliveryCompany);
     43        order.setPayment(payment);
     44        order.setOrderDate(LocalDate.now());
     45        order.setExpectedArrivalDate(LocalDate.now().plusDays(7));
     46        order.setStatus("во тек");
     47        order.setTotalPrice(finalAmount);
     48
     49        shoppingCartService.getMedicinesInCart(cart).forEach((medicine, qty) -> {
     50            ClientorderBrandedmedicine line = new ClientorderBrandedmedicine();
     51            ClientorderBrandedmedicineId id = new ClientorderBrandedmedicineId();
     52            id.setBrandedMedicineId(medicine.getId());
     53            line.setId(id);
     54            line.setOrder(order);
     55            line.setBrandedMedicine(medicine);
     56            line.setQuantity(qty);
     57            order.getItems().add(line);
     58        });
     59
     60        for (ClientorderBrandedmedicine line : order.getItems()) {
     61            int remaining = line.getQuantity();
     62            Integer bmId = line.getBrandedMedicine().getId();
     63
     64            List<InventoryBrandedmedicine> facilities =
     65                    inventoryBrandedmedicineRepository.lockAllByMedicineInPharmacies(bmId);
     66
     67            for (InventoryBrandedmedicine ibm : facilities) {
     68                if (remaining <= 0) break;
     69                int take = Math.min(ibm.getQuantity(), remaining);
     70                if (take <= 0) continue;
     71
     72                ibm.setQuantity(ibm.getQuantity() - take);
     73                ibm.setLastChanged(LocalDate.now());
     74                inventoryBrandedmedicineRepository.save(ibm);
     75
     76                remaining -= take;
     77            }
     78
     79            if (remaining > 0) {
     80                throw new IllegalStateException("Insufficient stock for medicine id=" + bmId);
     81            }
     82        }
     83        order.setStatus("во тек");
     84
     85        orderRepo.save(order);
     86
     87        payment.setStatus("завршено");
     88        paymentRepo.save(payment);
     89
     90        shoppingCartService.clearCart(cart);
     91
     92        return order;
     93    }
     94}}}
     95
     96=== 2. Зачувување на брендиран лек ===
     97{{{
     98    @Transactional(
     99            rollbackFor = { Exception.class, java.io.IOException.class },
     100            isolation = Isolation.READ_COMMITTED,
     101            propagation = Propagation.REQUIRED,
     102            timeout = 30
     103    )
     104    public void saveAll(Integer id,
     105                        Integer manufacturerId,
     106                        BigDecimal price,
     107                        String description,
     108                        String dosageForm,
     109                        String strength,
     110                        String originCountry,
     111                        String name,
     112                        MultipartFile[] newImages,
     113                        List<Integer> removeImageIds,
     114                        Integer mainExistingId,
     115                        Integer mainNewIndex) throws IOException {
     116
     117        Brandedmedicine bm;
     118        if (id == null) {
     119            bm = new Brandedmedicine();
     120        } else {
     121            bm = brandedMedicineRepository.findById(id)
     122                    .orElseThrow(() -> new EntityNotFoundException("Branded medicine not found: " + id));
     123        }
     124
     125        Manufacturer m = manufacturerRepository.findById(manufacturerId)
     126                .orElseThrow(() -> new EntityNotFoundException("Manufacturer not found: " + manufacturerId));
     127        bm.setManufacturer(m);
     128        bm.setPrice(price);
     129        bm.setDescription(description);
     130        bm.setDosageForm(dosageForm);
     131        bm.setStrength(strength);
     132        bm.setOriginCountry(originCountry);
     133        bm.setName(name);
     134
     135        Brandedmedicine saved = brandedMedicineRepository.save(bm);
     136
     137        if (removeImageIds != null && !removeImageIds.isEmpty()) {
     138            List<Brandedmedicineimage> toRemove = brandedMedicineImageRepository.findAllById(removeImageIds);
     139            for (Brandedmedicineimage img : toRemove) {
     140                if (!Objects.equals(img.getBrandedMedicine().getId(), saved.getId())) continue;
     141                deletePhysicalFileIfExists(img.getImage());
     142            }
     143            brandedMedicineImageRepository.deleteAll(toRemove);
     144        }
     145
     146        List<Brandedmedicineimage> appended = new ArrayList<>();
     147        if (newImages != null) {
     148            Path base = ensureUploadPath();
     149            long ts = System.currentTimeMillis();
     150            int seq = 0;
     151            for (MultipartFile file : newImages) {
     152                if (file == null || file.isEmpty()) continue;
     153                validateImageFile(file);
     154
     155                String original = Optional.ofNullable(file.getOriginalFilename()).orElse("image");
     156                String ext = getFileExtension(original).toLowerCase(Locale.ROOT);
     157                String filename = String.format("branded_medicine_%d_%d_%03d.%s", saved.getId(), ts, ++seq, ext);
     158
     159                Path dest = base.resolve(filename);
     160                Files.copy(file.getInputStream(), dest, StandardCopyOption.REPLACE_EXISTING);
     161
     162                String url = "/uploads/images/branded_medicine/" + filename;
     163
     164                Brandedmedicineimage img = new Brandedmedicineimage();
     165                img.setBrandedMedicine(saved);
     166                img.setImage(url);
     167                img.setMainImage(false);
     168                appended.add(brandedMedicineImageRepository.save(img));
     169            }
     170        }
     171
     172        Integer targetMainId = null;
     173
     174        if (mainExistingId != null) {
     175            brandedMedicineImageRepository.findById(mainExistingId).ifPresent(img -> {
     176                if (Objects.equals(img.getBrandedMedicine().getId(), saved.getId())) {
     177                    // capture via array holder
     178                }
     179            });
     180            if (brandedMedicineImageRepository.findById(mainExistingId)
     181                    .filter(img -> Objects.equals(img.getBrandedMedicine().getId(), saved.getId()))
     182                    .isPresent()) {
     183                targetMainId = mainExistingId;
     184            }
     185        }
     186
     187        if (targetMainId == null && mainNewIndex != null) {
     188            if (mainNewIndex >= 0 && mainNewIndex < appended.size()) {
     189                targetMainId = appended.get(mainNewIndex).getId();
     190            }
     191        }
     192
     193        if (targetMainId == null) {
     194            Optional<Brandedmedicineimage> curMain = brandedMedicineImageRepository
     195                    .findFirstByBrandedMedicineIdAndMainImageTrue(saved.getId());
     196            if (curMain.isPresent()) {
     197                targetMainId = curMain.get().getId();
     198            } else {
     199                targetMainId = brandedMedicineImageRepository
     200                        .findFirstByBrandedMedicineIdOrderByIdAsc(saved.getId())
     201                        .map(Brandedmedicineimage::getId).orElse(null);
     202            }
     203        }
     204
     205        if (targetMainId != null) {
     206            List<Brandedmedicineimage> all = brandedMedicineImageRepository.findByBrandedMedicineId(saved.getId());
     207            for (Brandedmedicineimage img : all) {
     208                boolean shouldBeMain = Objects.equals(img.getId(), targetMainId);
     209                if (img.isMainImage() != shouldBeMain) {
     210                    img.setMainImage(shouldBeMain);
     211                    brandedMedicineImageRepository.save(img);
     212                }
     213            }
     214        }
     215    }
     216}}}
     217
     218=== 3. Потврда за апликација на клиент да биде верифициран корисник ==
     219
     220{{{
     221    @Override
     222    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED, timeout = 10)
     223    public void approve(Integer id) {
     224        Sensitiveclientdata row = sensitiveRepo.findById(id)
     225                .orElseThrow(() -> new EntityNotFoundException("Application not found"));
     226        row.setVerificationStatus("одобрена");
     227        sensitiveRepo.save(row);
     228        Integer clientId = row.getClient().getId();
     229        Client client = clientRepo.findById(clientId)
     230                .orElseThrow(() -> new EntityNotFoundException("Client not found"));
     231        client.setIsVerified(Boolean.TRUE);
     232        clientRepo.save(client);
     233    }
     234
     235
     236}}}