private void RedeemBySomeoneCompletedEventHandler(
            Swap swap,
            byte[] secret,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Handle redeem party control completed event for swap {@swapId}", swap.Id);

            if (swap.IsAcceptor)
            {
                swap.Secret      = secret;
                swap.StateFlags |= SwapStateFlags.IsRedeemConfirmed;
                RaiseSwapUpdated(swap, SwapStateFlags.IsRedeemConfirmed);

                // get transactions & update balance for address async
                AddressHelper.UpdateAddressBalanceAsync <ERC20WalletScanner, ERC20Account, EthereumAccount>(
                    account: Erc20Account,
                    baseAccount: EthereumAccount,
                    address: swap.ToAddress,
                    cancellationToken: cancellationToken)
                .FireAndForget();
            }
        }
Exemple #2
0
        public void Address_should_produce_different_bytes_for_all_possible_network_and_account_types()
        {
            var cartesianProduct = AddressHelper.GetAllNetworksAndAccountTypesCombinations();

            var addressTypes = cartesianProduct.ToList();
            var forOutput    = addressTypes.Select(x =>
                                                   $"{Convert.ToString((int) x.NetworkType | (int) x.AccountType, 2).PadLeft(6, '0')} =>  {x.NetworkType}|{x.AccountType}");

            forOutput.ToList().ForEach(o => _output.WriteLine(o));

            var pubKeyBytes = ByteUtil.GenerateRandomByteArray(new FfiWrapper().PublicKeyLength);

            var addressesFromSamePubkey = addressTypes.Select(t => new Address
            {
                PublicKeyHash = pubKeyBytes.ToByteString(),
                AccountType   = t.AccountType,
                NetworkType   = t.NetworkType
            }).ToList();

            addressesFromSamePubkey
            .Select(a => a.RawBytes.ToByteString().ToBase64()).Should().OnlyHaveUniqueItems();
        }
Exemple #3
0
        private (List <Transaction>, List <Hash>) GenerateFakeTransactions(int count)
        {
            var transactions   = new List <Transaction>();
            var transactionIds = new List <Hash>();

            for (int i = 0; i < count; i++)
            {
                var transaction = new Transaction()
                {
                    From       = AddressHelper.Base58StringToAddress("z1NVbziJbekvcza3Zr4Gt4eAvoPBZThB68LHRQftrVFwjtGVM"),
                    To         = AddressHelper.Base58StringToAddress("2vNDCj1WjNLAXm3VnEeGGRMw3Aab4amVSEaYmCyxQKjNhLhfL7"),
                    MethodName = $"Test{i}",
                    Params     = ByteString.Empty
                };
                var hash = transaction.GetHash();

                transactions.Add(transaction);
                transactionIds.Add(hash);
            }

            return(transactions, transactionIds);
        }
Exemple #4
0
        public CheckResult <AddressDTO> CheckAddress(CallSource callSource, AddressDTO inputAddress)
        {
            //outputAddress = null;

            var fedexApi = new FedexAddressApi(_log,
                                               _time,
                                               _addressProviderInfo.EndPoint,
                                               _addressProviderInfo.UserName,
                                               _addressProviderInfo.Password,
                                               _addressProviderInfo.Key1,
                                               _addressProviderInfo.Key2,
                                               _addressProviderInfo.Key3,
                                               _portalName);

            //Should be only if UI call
            if (callSource == CallSource.UI)
            {
                //Ignore address2
                inputAddress.Address2 = "";
            }
            var searchString = AddressHelper.ToString(inputAddress, " ");
            var result       = fedexApi.ValidateAddress(inputAddress);

            var isValid = result != null &&
                          result.Data != null &&
                          result.Data.ValidationStatus < (int)AddressValidationStatus.Invalid;

            return(new CheckResult <AddressDTO>()
            {
                Status = isValid ? (int)AddressValidationStatus.Valid : (int)AddressValidationStatus.Invalid,
                Message = "Effective Address: " + StringHelper.Join(", ", result.Data.Address1, result.Data.Address2, result.Data.City, result.Data.State, result.Data.Zip, result.Data.Country),
                AdditionalData = new List <string>()
                {
                    OrderNotifyType.AddressCheckFedex.ToString(), result.Data?.IsResidential.ToString(), result.Data?.State
                },
                Data = result.Data
            });
        }
Exemple #5
0
 private ReportInvoiceVM GetReportInvoiceVM(Lead lead, LeadAssignment assignment
                                            , LeadState submittedState, LeadAssignmentState assignedState, LeadAssignmentState acceptedState
                                            , LeadAssignmentState currentState, StateAction currentAction)
 {
     return(new ReportInvoiceVM()
     {
         LeadId = lead.Id,
         LeadDetails = lead.Details,
         SubmittedDateTime = DateHelper.ConvertFromUtc(submittedState.ActionTimestamp),
         SubmittedDateTimeString = DateHelper.ConvertFromUtc(submittedState.ActionTimestamp).ToShortDateString() + " " + DateHelper.ConvertFromUtc(submittedState.ActionTimestamp).ToShortTimeString(),
         LeadTypeId = lead.LeadType.Id,
         LeadTypeName = lead.LeadType.Name,
         LeadTypeImage = ImageHelper.PATH_CLIENT_LEAD_TYPE + lead.LeadType.Image,
         LeadTypePrice = lead.LeadType.Price,
         CustomerId = lead.Customer.Id,
         CustomerUnique = lead.Customer.ContactName + " (" + lead.Customer.EMail + ")",
         CustomerName = lead.Customer.ContactName,
         CustomerContactNumber = lead.Customer.ContactNumber,
         CustomerEmail = lead.Customer.EMail,
         CustomerBusinessName = lead.Customer.BusinessName,
         CustomerState = lead.Customer.Address.State,
         CustomerAddress = AddressHelper.MergeAddress(lead.Customer.Address),
         PartnerId = assignment.PartnerBranch.Partner.Id,
         PartnerName = assignment.PartnerBranch.Partner.Name,
         PartnerLogo = ImageHelper.PATH_CLIENT_PARTNER + assignment.PartnerBranch.Partner.Logo,
         PartnerAddress = AddressHelper.MergeAddress(assignment.PartnerBranch.Address),
         LeadAssignmentId = assignment.Id,
         AssignedDateTime = DateHelper.ConvertFromUtc(assignedState.ActionTimestamp),
         AssignedDateTimeString = DateHelper.ConvertFromUtc(assignedState.ActionTimestamp).ToShortDateString() + " " + DateHelper.ConvertFromUtc(assignedState.ActionTimestamp).ToShortTimeString(),
         AcceptedDateTime = DateHelper.ConvertFromUtc(acceptedState.ActionTimestamp),
         AcceptedDateTimeString = DateHelper.ConvertFromUtc(acceptedState.ActionTimestamp).ToShortDateString() + " " + DateHelper.ConvertFromUtc(acceptedState.ActionTimestamp).ToShortTimeString(),
         CurrentStateId = currentState.State.Id,
         CurrentStateName = currentState.State.Name,
         CurrentStateTag = StatusHelper.GetHtmlBadge(currentState.State.Id, currentState.State.Name),
         CurrentActionId = currentAction.Action.Id,
         CurrentActionName = currentAction.Action.ActionName
     });
 }
Exemple #6
0
        public async Task InitContractInfoCacheAsync()
        {
            if (!_contractInfoCache.IsEmpty)
            {
                return;
            }

            var chainContractInfo = await _blockchainStateManager.GetChainContractInfoAsync();

            if (chainContractInfo.ContractInfos.IsNullOrEmpty())
            {
                return;
            }
            var chainStateInfo = await _blockchainStateManager.GetChainStateInfoAsync();

            chainContractInfo.ContractInfos.RemoveAll(c => c.Value <= chainStateInfo.BlockHeight);
            await _blockchainStateManager.SetChainContractInfoAsync(chainContractInfo);

            foreach (var key in chainContractInfo.ContractInfos.Keys)
            {
                _contractInfoCache[AddressHelper.Base58StringToAddress(key)] = chainContractInfo.ContractInfos[key];
            }
        }
Exemple #7
0
        public void PreCondition_Check_Test()
        {
            Func <Address> func1 = null;

            Should.Throw <ArgumentException>(() => Preconditions.CheckNotNull(func1));

            func1 = () => AddressHelper.Base58StringToAddress("z1NVbziJbekvcza3Zr4Gt4eAvoPBZThB68LHRQftrVFwjtGVM");
            var reference = Preconditions.CheckNotNull(func1);

            reference.ShouldNotBeNull();
            var addressInfo = reference();

            addressInfo.ShouldNotBeNull();
            addressInfo.GetType().ToString().ShouldBe("AElf.Types.Address");

            Func <Address, string> func2 = address => address.GetFormatted();
            var reference1 = Preconditions.CheckNotNull(func2, "address");

            reference1.ShouldNotBeNull();
            var result = reference1(AddressHelper.Base58StringToAddress("z1NVbziJbekvcza3Zr4Gt4eAvoPBZThB68LHRQftrVFwjtGVM"));

            result.ShouldNotBeNullOrEmpty();
        }
        private async Task RedeemBySomeoneCompletedEventHandler(
            Swap swap,
            byte[] secret,
            CancellationToken cancellationToken = default)
        {
            Log.Debug("Handle redeem party control completed event for swap {@swapId}", swap.Id);

            if (swap.IsAcceptor)
            {
                swap.Secret      = secret;
                swap.StateFlags |= SwapStateFlags.IsRedeemConfirmed;

                await UpdateSwapAsync(swap, SwapStateFlags.IsRedeemConfirmed, cancellationToken)
                .ConfigureAwait(false);

                // get transactions & update balance for address async
                _ = AddressHelper.UpdateAddressBalanceAsync <Erc20WalletScanner, Erc20Account, EthereumAccount>(
                    account: Erc20Account,
                    baseAccount: EthereumAccount,
                    address: swap.ToAddress,
                    cancellationToken: cancellationToken);
            }
        }
        public async Task <IActionResult> OnGetAsync(Guid addressId)
        {
            if (addressId == null)
            {
                return(RedirectToPage("./Index"));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(RedirectToPage("/Account/Login"));
            }

            Address = await _context.Addresses.FirstOrDefaultAsync(m => m.Id == addressId);

            if (Address == null)
            {
                return(RedirectToPage("./Index"));
            }

            Countries = new List <SelectListItem>();
            Countries.AddRange(AddressHelper.GetCountries().Select(keyValue => new SelectListItem()
            {
                Value = keyValue.Key,
                Text  = keyValue.Value
            }).OrderBy(x => x.Text));

            Provinces = new List <SelectListItem>();
            Provinces.AddRange(AddressHelper.GetProvinces().Select(keyValue => new SelectListItem()
            {
                Value = keyValue.Key,
                Text  = keyValue.Value
            }).OrderBy(x => x.Text));

            return(Page());
        }
        public AlreadyShippedEmailInfo(IAddressService addressService,
                                       string byName,
                                       string orderNumber,
                                       MarketType market,
                                       IList <ListingOrderDTO> items,
                                       string carrier,
                                       string trackingNumber,
                                       AddressDTO address,
                                       string buyerName,
                                       string buyerEmail) : base(addressService)
        {
            ByName = byName;
            Tag    = orderNumber;
            Market = market;

            Items          = items;
            Carrier        = carrier;
            TrackingNumber = trackingNumber;

            FullAddress = AddressHelper.ToStringForLetterWithPersonName(address);

            ToName  = StringHelper.MakeEachWordFirstLetterUpper(buyerName);
            ToEmail = buyerEmail;
        }
Exemple #11
0
        public List <OsmCity> GetCities()
        {
            requestCounter.City++;

            var cities = new List <OsmCity>();

            try {
                using (var connection = GetPostgisConnection()) {
                    connection.Open();
                    using (var cmd = new NpgsqlCommand()) {
                        cmd.Connection = connection;

                        // Insert some data
                        cmd.CommandText = "SELECT osm_cities.id, osm_cities.name, osm_cities.place, osm_suburb_districts.name " +
                                          "FROM osm_cities " +
                                          "LEFT JOIN osm_suburb_districts ON osm_suburb_districts.id = osm_cities.suburb_district_id " +
                                          "AND osm_cities.name IS NOT NULL AND osm_cities.name <> '';";
                        using (var reader = cmd.ExecuteReader()) {
                            while (reader.Read())
                            {
                                long   id       = reader.IsDBNull(0) ? 0 : reader.GetInt64(0);
                                string name     = reader.IsDBNull(1) ? String.Empty : reader.GetString(1);
                                string locality = reader.IsDBNull(2) ? String.Empty : reader.GetString(2);
                                string district = reader.IsDBNull(3) ? String.Empty : reader.GetString(3);
                                cities.Add(new OsmCity(id, name, district, AddressHelper.GetLocalityTypeByName(locality)));
                            }
                        }
                    }
                }
                cities.Sort(new OsmCityComparer());
            }
            catch (Exception ex) {
                logger.Error(ex, "Ошибка при получении списка городов.");
            }
            return(cities);
        }
Exemple #12
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var validationResults = new List <ValidationResult>();

            try
            {
                AddressHelper.Base58StringToAddress(From);
            }
            catch
            {
                validationResults.Add(new ValidationResult(Error.Message[Error.InvalidAddress],
                                                           new[] { nameof(From) }));
            }

            try
            {
                AddressHelper.Base58StringToAddress(To);
            }
            catch
            {
                validationResults.Add(
                    new ValidationResult(Error.Message[Error.InvalidAddress], new[] { nameof(To) }));
            }

            try
            {
                HashHelper.HexStringToHash(RefBlockHash);
            }
            catch
            {
                validationResults.Add(
                    new ValidationResult(Error.Message[Error.InvalidBlockHash], new[] { nameof(RefBlockHash) }));
            }

            return(validationResults);
        }
        /// <summary>
        /// Creates an unsigned serialized transaction
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <CreateRawTransactionOutput> CreateRawTransactionAsync(CreateRawTransactionInput input)
        {
            var transaction = new Transaction
            {
                From           = AddressHelper.Base58StringToAddress(input.From),
                To             = AddressHelper.Base58StringToAddress(input.To),
                RefBlockNumber = input.RefBlockNumber,
                RefBlockPrefix = ByteString.CopyFrom(HashHelper.HexStringToHash(input.RefBlockHash).Value.Take(4).ToArray()),
                MethodName     = input.MethodName
            };
            var methodDescriptor = await GetContractMethodDescriptorAsync(AddressHelper.Base58StringToAddress(input.To), input.MethodName);

            if (methodDescriptor == null)
            {
                throw new UserFriendlyException(Error.Message[Error.NoMatchMethodInContractAddress],
                                                Error.NoMatchMethodInContractAddress.ToString());
            }
            try
            {
                var parameters = methodDescriptor.InputType.Parser.ParseJson(input.Params);
                if (!IsValidMessage(parameters))
                {
                    throw new UserFriendlyException(Error.Message[Error.InvalidParams], Error.InvalidParams.ToString());
                }
                transaction.Params = parameters.ToByteString();
            }
            catch
            {
                throw new UserFriendlyException(Error.Message[Error.InvalidParams], Error.InvalidParams.ToString());
            }

            return(new CreateRawTransactionOutput
            {
                RawTransaction = transaction.ToByteArray().ToHex()
            });
        }
        /// <summary>
        /// Updates the group the asset should belong to.
        /// Assets will be stored in groups for the Locale they are used by unless they are used
        /// by more than 1 <see cref="Locale"/>, then they will be moved to the shared group.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="assetEntry"></param>
        /// <param name="createUndo">Used to indicate if an Undo operation should be created.</param>
        protected virtual void UpdateAssetGroup(AddressableAssetSettings settings, AddressableAssetEntry assetEntry, bool createUndo)
        {
            if (settings == null || assetEntry == null)
            {
                return;
            }

            // Find all the locales that are using the asset using the Addressable labels.
            var localesUsingAsset = assetEntry.labels.Where(AddressHelper.IsLocaleLabel);

            if (localesUsingAsset.Count() == 0)
            {
                var oldGroup = assetEntry.parentGroup;
                settings.RemoveAssetEntry(assetEntry.guid);
                if (oldGroup.entries.Count == 0)
                {
                    if (createUndo)
                    {
                        // We cant use undo asset deletion so we will leave an empty group instead of deleting it.
                        Undo.RecordObject(oldGroup, "Remove group");
                    }
                    else
                    {
                        settings.RemoveGroup(oldGroup);
                    }
                }

                return;
            }

            AddressableAssetGroup newGroup;

            if (localesUsingAsset.Count() == 1)
            {
                // If only 1 locale is using the asset then we will add it to a locale specific group.
                var localeId = AddressHelper.LocaleLabelToId(localesUsingAsset.First());
                newGroup = LocalizationEditorSettings.Instance.GetGroup(settings, FormatAssetTableCollectionName(localeId), true, createUndo);
            }
            else
            {
                // More than one locale uses the asset so it goes to the shared assets group.
                newGroup = LocalizationEditorSettings.Instance.GetGroup(settings, LocalizationEditorSettings.SharedAssetGroupName, true, createUndo);
            }

            // Do we need to change the asset's group?
            if (newGroup != assetEntry.parentGroup)
            {
                if (createUndo)
                {
                    Undo.RecordObject(newGroup, "Update asset group");
                    Undo.RecordObject(assetEntry.parentGroup, "Update asset group");
                }

                var oldGroup = assetEntry.parentGroup;
                settings.MoveEntry(assetEntry, newGroup, true);
                if (oldGroup.entries.Count == 0)
                {
                    // We only delete the asset when not creating an undo as we can not undo asset deletion.
                    if (!createUndo)
                    {
                        settings.RemoveGroup(oldGroup);
                    }
                }
            }
        }
        /// <summary>
        /// Remove the asset mapping from the table entry and also cleans up the Addressables if necessary.
        /// </summary>
        /// <param name="table"></param>
        /// <param name="entryReference"></param>
        /// <param name="createUndo"></param>
        public void RemoveAssetFromTable(AssetTable table, TableEntryReference entryReference, bool createUndo = false)
        {
            var undoGroup = Undo.GetCurrentGroup();

            if (createUndo)
            {
                Undo.RecordObject(table, "Remove asset from table");            // We modify the table entry.
                Undo.RecordObject(table.SharedData, "Remove asset from table"); // We modify the shared table metadata.
            }
            //else // Asset changes are not being saved correctly at the moment when using Undo. (LOC-82)
            {
                EditorUtility.SetDirty(table);
                EditorUtility.SetDirty(table.SharedData);
            }

            // Clear the asset but keep the key
            var tableEntry = table.GetEntryFromReference(entryReference);

            if (tableEntry == null)
            {
                return;
            }

            var removedAssetGuid = tableEntry.Guid;

            tableEntry.Guid = string.Empty;

            var aaSettings = LocalizationEditorSettings.Instance.GetAddressableAssetSettings(false);

            if (aaSettings == null)
            {
                return;
            }

            // Update type metadata
            // We cant use a foreach here as we are sometimes inside of a loop and exceptions will be thrown (Collection was modified).
            for (int i = 0; i < table.SharedData.Metadata.MetadataEntries.Count; ++i)
            {
                var md = table.SharedData.Metadata.MetadataEntries[i];
                if (md is AssetTypeMetadata at)
                {
                    if (at.Contains(tableEntry.KeyId))
                    {
                        tableEntry.RemoveSharedMetadata(at);
                    }
                }
            }

            // If the entry has metadata then we will leave an empty entry otherwise we just remove the whole thing.
            if (tableEntry.MetadataEntries.Count == 0)
            {
                table.RemoveEntry(tableEntry.KeyId);
            }

            // Determine if the asset is being referenced by any entries or tables with the same locale, if not then we can
            // remove the locale label and if no other labels exist also remove the asset from the Addressables system.
            var assetTableCollections = LocalizationEditorSettings.GetAssetTableCollections();

            foreach (var collection in assetTableCollections)
            {
                var tableWithMatchingLocaleId = collection.GetTable(table.LocaleIdentifier) as AssetTable;
                if (tableWithMatchingLocaleId == null)
                {
                    continue;
                }

                if (tableWithMatchingLocaleId.ContainsValue(removedAssetGuid))
                {
                    // The asset is referenced elsewhere so we can not remove the label or asset.
                    return;
                }
            }

            // Remove the locale label for this asset
            var assetEntry = aaSettings.FindAssetEntry(removedAssetGuid);

            if (assetEntry != null)
            {
                if (createUndo)
                {
                    Undo.RecordObject(assetEntry.parentGroup, "Remove asset from table");
                }

                var assetLabel = AddressHelper.FormatAssetLabel(table.LocaleIdentifier);
                assetEntry.SetLabel(assetLabel, false);
                UpdateAssetGroup(aaSettings, assetEntry, createUndo);
            }

            if (createUndo)
            {
                Undo.CollapseUndoOperations(undoGroup);
            }

            LocalizationEditorSettings.EditorEvents.RaiseAssetTableEntryRemoved(this, table, tableEntry, removedAssetGuid);
        }
Exemple #16
0
        public bool IsAccept(OrderToTrackDTO orderToTrackInfo,
                             string status,
                             DateTime?statusDate,
                             IList <TrackingRecord> records)
        {
            var now   = _time.GetAppNowTime();
            var today = _time.GetAppNowTime().Date;

            var lastRecord    = records.FirstOrDefault();
            var packageGoBack = (lastRecord != null ? _addressService.IsMine(lastRecord.AsAddressDto()) : false) ||
                                orderToTrackInfo.DeliveredStatus == (int)DeliveredStatusEnum.DeliveredToSender;

            //почта после 60 дней за них не отвечает
            //старше 55 дней
            if (statusDate.HasValue &&
                statusDate.Value.AddDays(55) < today)
            {
                return(false);
            }

            if (packageGoBack)
            {
                return(false); //No actions if package go back
            }
            if (orderToTrackInfo.Carrier == ShippingServiceUtils.USPSCarrier)
            {
                if (statusDate.HasValue &&
                    !_time.IsBusinessDay(statusDate.Value) &&
                    _time.GetBizDaysCount(statusDate.Value, today) < 2)
                {
                    //TASK: Let’s not send Exception messages for First Class packages if they were not delivered on Weekends/holidays.
                    if (orderToTrackInfo.ShippingMethodId.HasValue
                        &&
                        ShippingUtils.GetShippingType(orderToTrackInfo.ShippingMethodId.Value) ==
                        ShippingTypeCode.Standard)
                    {
                        //Don’t send notice to first class orders which USPS tried to deliver on Saturday.
                        //They will automatically will redeliver it on the next business day.
                        return(false);
                    }


                    //TASK: if any package couldn’t be delivered to FF on weekends/holidays
                    if (AddressHelper.IsFFAddress(orderToTrackInfo.ShippingAddress))
                    {
                        return(false);
                    }
                }

                //TASK: If First Class order wasn’t delivered like 102-1600419-5915438 check again in 24 hours, and only then send notifications.
                if (orderToTrackInfo.ShippingMethodId.HasValue
                    &&
                    ShippingUtils.GetShippingType(orderToTrackInfo.ShippingMethodId.Value) == ShippingTypeCode.Standard)
                {
                    var statusNextBusiessDay = _time.AddBusinessDays(statusDate, 1);
                    if (statusNextBusiessDay > now)
                    {
                        return(false);
                    }
                }

                if (!String.IsNullOrEmpty(status) &&
                    (status.IndexOf("Notice Left", StringComparison.InvariantCultureIgnoreCase) >= 0 ||
                     status.IndexOf("Receptacle Blocked", StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                     status.IndexOf("Available for Pickup", StringComparison.InvariantCultureIgnoreCase) >= 0 ||
                     status.IndexOf("Business Closed", StringComparison.OrdinalIgnoreCase) >= 0 ||
                     status.IndexOf("Undeliverable as Addressed", StringComparison.OrdinalIgnoreCase) >= 0 ||
                     status.IndexOf("Addressee not available", StringComparison.OrdinalIgnoreCase) >= 0) &&
                    statusDate.HasValue)
                {
                    return(true);
                }
            }

            if (orderToTrackInfo.Carrier == ShippingServiceUtils.DHLCarrier ||
                orderToTrackInfo.Carrier == ShippingServiceUtils.DHLMXCarrier)
            {
                if (!String.IsNullOrEmpty(status) &&
                    status.IndexOf("Delivery attempted; recipient not home", StringComparison.InvariantCultureIgnoreCase) >= 0 &&
                    statusDate.HasValue)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #17
0
        /// <summary>
        /// 达达运费
        /// </summary>
        /// <param name="cityName"></param>
        /// <param name="appid"></param>
        /// <param name="openid"></param>
        /// <param name="lat"></param>
        /// <param name="lnt"></param>
        /// <param name="accepterName"></param>
        /// <param name="accepterPhone"></param>
        /// <param name="address"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int GetDadaFee(string cityName, string appid, string openid, string accepterName, string accepterPhone, string address, string lat, string lnt, ref string msg)
        {
            if (string.IsNullOrEmpty(appid))
            {
                msg = "appid不能为空";
                return(0);
            }
            if (!string.IsNullOrEmpty(address))
            {
                //再请求一次腾讯地图,获取准确的坐标
                AddressApi addressModel = AddressHelper.GetLngAndLatByAddress(address);
                if (addressModel != null && addressModel.result != null && addressModel.result.location != null)
                {
                    lnt = addressModel.result.location.lng.ToString();
                    lat = addressModel.result.location.lat.ToString();
                }
                else
                {
                    msg = "达达配送:获取腾讯地址失败";
                    return(0);
                }
            }

            XcxAppAccountRelation umodel = XcxAppAccountRelationBLL.SingleModel.GetModelByAppid(appid);

            if (umodel == null)
            {
                msg = "达达配送:权限模板不能为空";
                return(0);
            }
            C_UserInfo userInfo = C_UserInfoBLL.SingleModel.GetModelByAppId_OpenId(appid, openid);

            if (userInfo == null)
            {
                msg = "达达配送:用户不存在";
                return(0);
            }
            if (accepterName == null || accepterName.Length == 0)
            {
                msg = "达达配送:收货人姓名不能为空";
                return(0);
            }
            if (accepterPhone == null || accepterPhone.Length == 0)
            {
                msg = "达达配送:收货人手机号不能为空";
                return(0);
            }
            if (address == null || address.Length == 0)
            {
                msg = "达达配送:收货人地址不能为空";
                return(0);
            }

            DadaMerchant merchant = DadaMerchantBLL.SingleModel.GetModelByRId(umodel.Id);

            if (merchant == null || merchant.id <= 0)
            {
                msg = "达达配送:商户还没开通达达配送";
                return(0);
            }

            try
            {
                DadaOrder dadaOrderModel = GetDadaOrderModel(merchant.id, userInfo.Id, 0, cityName, 0, accepterName, accepterPhone, address, Convert.ToDouble(lat), Convert.ToDouble(lnt), "", ref msg);
                if (dadaOrderModel == null || !string.IsNullOrEmpty(msg))
                {
                    msg = $"达达配送:获取物流运费失败:" + msg;
                    return(0);
                }

                DadaApiReponseModel <ResultReponseModel> postData = AddOrder(dadaOrderModel, merchant.sourceid, 2);
                if (postData != null && postData.result != null)
                {
                    return(Convert.ToInt32(postData.result.deliverFee * 100));
                }

                log4net.LogHelper.WriteInfo(this.GetType(), "达达运费出错:" + JsonConvert.SerializeObject(postData) + ",请求参数=" + JsonConvert.SerializeObject(dadaOrderModel));

                msg = "获取运费出错";
            }
            catch (Exception ex)
            {
                msg = ex.Message + ",msg" + msg;
            }

            return(0);
        }
Exemple #18
0
        public void IsLocaleLabel_WorksWithLabelsGeneratedUsing_FormatAssetLabel(Locale locale)
        {
            var label = AddressHelper.FormatAssetLabel(locale.Identifier);

            Assert.IsTrue(AddressHelper.IsLocaleLabel(label), "Expected the Addressables Locale label to be recognized by IsLocaleLabel.");
        }
Exemple #19
0
        public void LocaleLabelToId_WorksWithLabelsGeneratedUsing_FormatAssetLabel(Locale locale)
        {
            var label = AddressHelper.FormatAssetLabel(locale.Identifier);

            LocaleLabelToId_CorrectlyConvertsLabel(label, locale.Identifier.Code);
        }
        public IList <CheckResult <AddressDTO> > CheckAddress(CallSource callSource,
                                                              IUnitOfWork db,
                                                              AddressDTO address,
                                                              long?orderId,
                                                              out AddressDTO addressWithCorrection)
        {
            if (orderId.HasValue && orderId.Value == 0)
            {
                throw new ArgumentOutOfRangeException("order.Id", "Should be non zero");
            }

            addressWithCorrection = null;

            var checkResults = _addressService.CheckAddress(callSource,
                                                            address);

            OrderNotify dbStampsOrderNotify = null;

            foreach (var subResult in checkResults)
            {
                //Stamps
                if (subResult.AdditionalData?[0] == OrderNotifyType.AddressCheckStamps.ToString())
                {
                    if (orderId.HasValue)
                    {
                        dbStampsOrderNotify = new OrderNotify()
                        {
                            OrderId    = orderId.Value,
                            Type       = (int)OrderNotifyType.AddressCheckStamps,
                            Message    = StringHelper.Substring(subResult.Message, 512),
                            Status     = (int)subResult.Status,
                            CreateDate = _time.GetAppNowTime()
                        };

                        db.OrderNotifies.Add(dbStampsOrderNotify);
                    }
                }

                //Previous correction address
                if (subResult.AdditionalData?[0] == OrderNotifyType.AddressCheckWithPerviousCorrection.ToString())
                {
                    addressWithCorrection = subResult.Data;

                    if (orderId.HasValue)
                    {
                        db.OrderNotifies.Add(new OrderNotify()
                        {
                            OrderId    = orderId.Value,
                            Type       = (int)OrderNotifyType.AddressCheckWithPerviousCorrection,
                            Message    = StringHelper.Substring(subResult.Message, 512),
                            Status     = subResult.Status,
                            CreateDate = _time.GetUtcTime()
                        });
                    }

                    if (subResult.Status < (int)AddressValidationStatus.Invalid &&
                        subResult.Status != (int)AddressValidationStatus.None)
                    {
                        if (addressWithCorrection != null &&
                            String.IsNullOrEmpty(addressWithCorrection.Address1) &&
                            String.IsNullOrEmpty(addressWithCorrection.Address2) &&
                            String.IsNullOrEmpty(addressWithCorrection.City) &&
                            String.IsNullOrEmpty(addressWithCorrection.State) &&
                            String.IsNullOrEmpty(addressWithCorrection.Country) &&
                            String.IsNullOrEmpty(addressWithCorrection.Zip) &&
                            String.IsNullOrEmpty(addressWithCorrection.ZipAddon))
                        {
                            addressWithCorrection = null;
                        }

                        if (addressWithCorrection != null)
                        {
                            /*
                             * Похоже идея автоматически менять адрес на предыдущий не совсем хорошая, есть клиент например который хотел послать посылку на новый адрес а мы послали на старый 110-4229580-1843404
                             * Давай теперь вместо автоматического исправления адреса просто писать коммент, «previous delivery to %Old_Address% was successful”
                             */

                            if (orderId.HasValue)
                            {
                                var addressString = AddressHelper.ToString(addressWithCorrection, ", ");

                                db.OrderComments.Add(new OrderComment()
                                {
                                    OrderId    = orderId.Value,
                                    Message    = String.Format("[System] Previous delivery to \"{0}\" was successful", addressString),
                                    Type       = (int)CommentType.Address,
                                    CreateDate = _time.GetUtcTime()
                                });
                            }

                            //NOTE: Previous correction address uses only to create order comment
                            addressWithCorrection = null;
                        }
                    }
                }

                if (subResult.AdditionalData?[0] == OrderNotifyType.AddressCheckMelissa.ToString())
                {
                    //Nothing
                }

                if (subResult.AdditionalData?[0] == OrderNotifyType.AddressCheckGoogleGeocode.ToString())
                {
                    if (orderId.HasValue)
                    {
                        db.OrderNotifies.Add(new OrderNotify()
                        {
                            OrderId    = orderId.Value,
                            Type       = (int)OrderNotifyType.AddressCheckGoogleGeocode,
                            Message    = StringHelper.Substring(subResult.Message, 512),
                            Status     = subResult.Status,
                            CreateDate = _time.GetUtcTime()
                        });
                    }
                }
                if (subResult.AdditionalData?[0] == OrderNotifyType.AddressCheckFedex.ToString())
                {
                    if (orderId.HasValue)
                    {
                        db.OrderNotifies.Add(new OrderNotify()
                        {
                            OrderId    = orderId.Value,
                            Type       = (int)OrderNotifyType.AddressCheckFedex,
                            Message    = StringHelper.Substring(subResult.Message, 512),
                            Status     = subResult.Status,
                            CreateDate = _time.GetUtcTime()
                        });
                    }

                    var stampsResult = checkResults.FirstOrDefault(r => r.AdditionalData[0] == OrderNotifyType.AddressCheckStamps.ToString());
                    if (stampsResult != null && stampsResult.Status >= (int)AddressValidationStatus.Invalid)
                    {
                        if (subResult.Status < (int)AddressValidationStatus.Invalid)
                        {
                            if (addressWithCorrection == null &&
                                subResult.Data != null)
                            {
                                var correctionCandidate = subResult.Data;
                                correctionCandidate.FullName = address.FullName;
                                //TASK: If stamps verify it replace it, and don’t show errors.
                                var addressCandidateResults = _addressService.CheckAddress(callSource,
                                                                                           correctionCandidate,
                                                                                           new Core.Models.Settings.AddressProviderType[] { Core.Models.Settings.AddressProviderType.Stamps });

                                var stampsCandidateResult = addressCandidateResults.FirstOrDefault(r => r.AdditionalData[0] == OrderNotifyType.AddressCheckStamps.ToString());
                                if (stampsCandidateResult.Status < (int)AddressValidationStatus.Invalid)
                                {
                                    _log.Info("Replacing address to Fedex Effective address");

                                    stampsResult.Status = stampsCandidateResult.Status;
                                    if (dbStampsOrderNotify != null)
                                    {
                                        dbStampsOrderNotify.Status = stampsCandidateResult.Status;
                                    }

                                    if (orderId.HasValue)
                                    {
                                        db.OrderComments.Add(new OrderComment()
                                        {
                                            OrderId    = orderId.Value,
                                            Message    = String.Format("[System] Address was replaced by Fedex \"Effective address\""),
                                            Type       = (int)CommentType.Address,
                                            CreateDate = _time.GetUtcTime()
                                        });
                                    }

                                    addressWithCorrection = subResult.Data;
                                }
                            }
                        }
                    }
                }
            }

            return(checkResults);
        }
 public ProvinceController()
 {
     db = new AddressHelper();
 }
        /// <summary>
        /// 指定宿主机环境
        /// </summary>
        /// <param name="hostBuilder"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder, string address, int port, string token = "True")
        {
            return(hostBuilder.MapServices(mapper =>
            {
                BuildServiceEngine(mapper);
                mapper.Resolve <IServiceCommandManager>().SetServiceCommandsAsync();
                var serviceToken = mapper.Resolve <IServiceTokenGenerator>().GeneratorToken(token);
                var _port = AppConfig.ServerOptions.Port == 0 ? port : AppConfig.ServerOptions.Port;
                var _address = AppConfig.ServerOptions.Ip ?? address;
                var _ip = AddressHelper.GetIpFromAddress(_address);

                _port = AppConfig.ServerOptions.IpEndpoint?.Port ?? _port;
                _ip = AppConfig.ServerOptions.IpEndpoint?.Address.ToString() ?? _ip;
                if (_ip.IndexOf(".") < 0 || _ip == "" || _ip == "0.0.0.0")
                {
                    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface adapter in nics)
                    {
                        if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet && (_ip == "" || _ip == "0.0.0.0" || _ip == adapter.Name))
                        {
                            IPInterfaceProperties ipxx = adapter.GetIPProperties();
                            UnicastIPAddressInformationCollection ipCollection = ipxx.UnicastAddresses;
                            foreach (UnicastIPAddressInformation ipadd in ipCollection)
                            {
                                if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                {
                                    _ip = ipadd.Address.ToString();
                                }
                            }
                        }
                    }
                }
                var mappingIp = AppConfig.ServerOptions.MappingIP ?? _ip;
                var mappingPort = AppConfig.ServerOptions.MappingPort;
                if (mappingPort == 0)
                {
                    mappingPort = _port;
                }

                if (string.IsNullOrEmpty(AppConfig.ServerOptions.MappingIP))
                {
                    ConfigureRoute(mapper, _ip, _port, serviceToken);
                }
                else
                {
                    ConfigureRoute(mapper, _ip, _port, mappingIp, mappingPort, serviceToken);
                }
                //初始化模块
                mapper.Resolve <IModuleProvider>().Initialize();
                //获取微服务主机(可能存在多个运行时主机,取决于微服务依赖的模块)
                var serviceHosts = mapper.Resolve <IList <Runtime.Server.IServiceHost> >();
                Task.Factory.StartNew(async() =>
                {
                    foreach (var serviceHost in serviceHosts)
                    {
                        await serviceHost.StartAsync(_ip, _port);
                    }
                    mapper.Resolve <IServiceEngineLifetime>().NotifyStarted();
                }).Wait();
            }));
        }
        public void Execute()
        {
            _contaAzulService.RefreshToken();

            var customers = _customerService.GetAllCustomers();

            // var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            CustomerResponse[] GetCustomerResponse = null;
            CustomerResponse   CustomerResponse    = null;
            var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>();

            var number     = string.Empty;
            var complement = string.Empty;
            var cpfCnpj    = string.Empty;

            foreach (var item in customers)
            {
                var customer = new CustomerMessage();

                new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null,
                                                                                                      out number, out complement, out cpfCnpj);

                customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null;

                customer.companyName           = item.BillingAddress != null ? item.BillingAddress.Company : null;
                customer.email                 = item.Email;
                customer.personType            = "NATURAL";
                customer.stateRegistrationType = "NO_CONTRIBUTOR";
                customer.mobilePhone           = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null;
                customer.address.city.name     = item.BillingAddress != null ? item.BillingAddress.City : null;
                customer.address.state.name    = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null;
                customer.address.zipCode       = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null;
                customer.address.street        = item.BillingAddress != null ? item.BillingAddress.Address1 : null;
                customer.address.complement    = complement;
                customer.address.number        = number;
                customer.document              = cpfCnpj == "" ? null : cpfCnpj;

                try
                {
                    var filtro = "?search=";
                    if (cpfCnpj == string.Empty)
                    {
                        filtro = filtro + item.Email;
                    }
                    else
                    {
                        filtro = filtro + cpfCnpj;
                    }
                    using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox))
                        GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult();
                    //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco
                    if (GetCustomerResponse.Count() > 0)
                    {
                        var customerTable = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]);
                        //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul
                        if (customerTable == null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = GetCustomerResponse[0].id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);

                            customer.id = customerTable.ContaAzulId.ToString();
                            customer.address.city.name = null;

                            var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]);
                            var data2 = JsonConvert.SerializeObject(customer);


                            // var data = data2.Equals(data1);

                            if (!data1.Equals(data2))
                            {
                                //se ele já existe na tabela, só faz o update no conta azul
                                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                    CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                            }
                        }
                        else
                        {
                            customer.id = customerTable.ContaAzulId.ToString();
                            customer.address.city.name = null;

                            var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]);
                            var data2 = JsonConvert.SerializeObject(customer);


                            var data = data2.Equals(data1);

                            if (!data1.Equals(data2))
                            {
                                //se ele já existe na tabela, só faz o update no conta azul
                                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                    CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerTable.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                            }
                        }
                    }
                    else
                    {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados
                        var data2 = JsonConvert.SerializeObject(customer);
                        using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                            CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                        if (CustomerResponse != null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = CustomerResponse.id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message, ex);
                }
            }
        }
Exemple #24
0
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            comboBoxCountry.ItemsSource = AddressHelper.GetCountries();

            comboBoxPhoneType.ItemsSource = PhoneHelper.GetPhoneTypes();
        }
Exemple #25
0
        public ActionResult AddStore()
        {
            returnObj      = new Return_Msg_APP();
            returnObj.code = "200";
            string appId       = Context.GetRequest("appId", string.Empty);
            int    userId      = Context.GetRequestInt("myCardId", 0);
            int    agentInfoId = Context.GetRequestInt("agentInfoId", 0);

            if (string.IsNullOrEmpty(appId) || userId <= 0)
            {
                returnObj.Msg = "参数错误";
                return(Json(returnObj));
            }

            XcxAppAccountRelation r = _xcxAppAccountRelationBLL.GetModelByAppid(appId);

            if (r == null)
            {
                returnObj.Msg = "小程序未授权";
                return(Json(returnObj, JsonRequestBehavior.AllowGet));
            }

            Agentinfo agentinfo = AgentinfoBLL.SingleModel.GetModelByAccoundId(r.AccountId.ToString());
            //if (agentinfo == null)//本平台代理信息
            //{
            //    returnObj.Msg = "入驻异常";
            //    return Json(returnObj, JsonRequestBehavior.AllowGet);
            //}

            string banners = Context.GetRequest("banners", string.Empty);

            if (string.IsNullOrEmpty(banners) || banners.Split(',').Length <= 0)
            {
                returnObj.Msg = "轮播图至少一张";
                return(Json(returnObj));
            }
            string storeName = Context.GetRequest("storeName", string.Empty);

            if (string.IsNullOrEmpty(storeName) || storeName.Length >= 20)
            {
                returnObj.Msg = "店铺名称不能为空并且不能超过20字符";
                return(Json(returnObj));
            }

            string lngStr = Context.GetRequest("lng", string.Empty);
            string latStr = Context.GetRequest("lat", string.Empty);
            double lng    = 0.00;
            double lat    = 0.00;

            if (!double.TryParse(lngStr, out lng) || !double.TryParse(latStr, out lat))
            {
                returnObj.Msg = "地址坐标错误";
                return(Json(returnObj));
            }

            string location = Context.GetRequest("location", string.Empty);

            if (string.IsNullOrEmpty(location))
            {
                returnObj.Msg = "地址不能为空";
                return(Json(returnObj));
            }

            string storeService = Context.GetRequest("storeService", string.Empty);
            //if (string.IsNullOrEmpty(storeService) || storeService.Split(',').Length <= 0)
            //{
            //    returnObj.Msg = "提供服务不能为空";
            //    return Json(returnObj);
            //}

            string openTime = Context.GetRequest("openTime", string.Empty);
            //if (string.IsNullOrEmpty(openTime))
            //{
            //    returnObj.Msg = "营业时间不能为空";
            //    return Json(returnObj);
            //}
            //TODO 需要验证手机+电话
            string phone = Context.GetRequest("phone", string.Empty);

            if (string.IsNullOrEmpty(phone))
            {
                returnObj.Msg = "请填写正确的号码";
                return(Json(returnObj));
            }

            string businessDescription = Context.GetRequest("businessDescription", string.Empty);

            if (string.IsNullOrEmpty(businessDescription))
            {
                returnObj.Msg = "业务简述不能为空";
                return(Json(returnObj));
            }

            string storeDescription = Context.GetRequest("storeDescription", string.Empty);
            string storeImgs        = Context.GetRequest("storeImgs", string.Empty);
            int    category         = Context.GetRequestInt("category", 0);//店铺类别

            if (PlatStoreCategoryBLL.SingleModel.GetModel(category) == null)
            {
                returnObj.Msg = "类别选择错误!";
                return(Json(returnObj));
            }

            PlatStore platStore = PlatStoreBLL.SingleModel.GetPlatStore(userId, 1);

            if (platStore == null)
            {
                platStore = new PlatStore();
            }

            AddressApi addressinfo = AddressHelper.GetAddressByApi(lngStr, latStr);

            if (addressinfo == null || addressinfo.result == null || addressinfo.result.address_component == null)
            {
                returnObj.Msg = "地址出错!";
                return(Json(returnObj));
            }

            if (!storeService.Contains("ServiceState"))
            {
                //表示旧版本的数据,设施服务给初始化新值
                List <StoreServiceModel> list = new List <StoreServiceModel>();
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "WIFI"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "停车位"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "支付宝支付"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "微信支付"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "刷卡支付"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "空调雅座"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "付费停车"
                });
                list.Add(new StoreServiceModel()
                {
                    ServiceState = true, ServiceName = "接送服务"
                });
                storeService = Newtonsoft.Json.JsonConvert.SerializeObject(list);
            }


            string storeRemark = Context.GetRequest("storeRemark", string.Empty);

            platStore.StoreRemark = storeRemark;

            string provinceName = addressinfo.result.address_component.province;
            string cityName     = addressinfo.result.address_component.city;
            string countryName  = addressinfo.result.address_component.district;

            platStore.ProvinceCode        = C_AreaBLL.SingleModel.GetCodeByName(provinceName);
            platStore.CityCode            = C_AreaBLL.SingleModel.GetCodeByName(cityName);
            platStore.CountryCode         = C_AreaBLL.SingleModel.GetCodeByName(countryName);
            platStore.AddTime             = DateTime.Now;
            platStore.Banners             = banners;
            platStore.BindPlatAid         = r.Id;
            platStore.BusinessDescription = businessDescription;
            platStore.Category            = category;
            platStore.Lat              = lat;
            platStore.Lng              = lng;
            platStore.Location         = location;
            platStore.MyCardId         = userId;
            platStore.Name             = storeName;
            platStore.OpenTime         = openTime;
            platStore.Phone            = phone;
            platStore.StoreDescription = storeDescription;
            platStore.StoreImgs        = storeImgs;
            platStore.StoreService     = storeService;
            platStore.UpdateTime       = DateTime.Now;
            TransactionModel TranModel = new TransactionModel();

            if (platStore.Id > 0)
            {
                //表示更新

                TranModel.Add(PlatStoreBLL.SingleModel.BuildUpdateSql(platStore));
                PlatStoreRelation platStoreRelation = PlatStoreRelationBLL.SingleModel.GetPlatStoreRelationOwner(r.Id, platStore.Id);
                if (platStoreRelation == null)
                {
                    returnObj.Msg = "更新异常(店铺关系找不到数据)";
                    return(Json(returnObj));
                }
                platStoreRelation.Category   = platStore.Category;
                platStoreRelation.UpdateTime = DateTime.Now;
                TranModel.Add(PlatStoreRelationBLL.SingleModel.BuildUpdateSql(platStoreRelation, "Category,UpdateTime"));

                //2.查找上级代理
                #region  步代理商店铺 暂时先屏蔽
                //AgentDistributionRelation agentDistributionRelationFirst = new AgentDistributionRelationBLL().GetModel(agentinfo.id);
                //if (agentDistributionRelationFirst != null)
                //{
                //    Agentinfo agentinfoFirst = _agentinfoBll.GetModel(agentDistributionRelationFirst.ParentAgentId);
                //    if (agentinfoFirst != null)
                //    {
                //        XcxAppAccountRelation xcxAppAccountRelationFirst = _xcxappaccountrelationBll.GetModelByaccountidAndTid(agentinfoFirst.useraccountid, (int)TmpType.小未平台);
                //        if (xcxAppAccountRelationFirst != null)
                //        {
                //            PlatStoreRelation platStoreRelationFist = _platStoreRelationBLL.GetPlatStoreRelationOwner(xcxAppAccountRelationFirst.Id, platStore.Id, agentinfo.id);
                //            if (platStoreRelationFist != null)
                //            {
                //                platStoreRelationFist.Category = platStore.Category;
                //                platStoreRelationFist.UpdateTime = DateTime.Now;
                //                TranModel.Add(_platStoreRelationBLL.BuildUpdateSql(platStoreRelationFist, "Category,UpdateTime"));
                //            }


                //            //3.查找上级的上级代理
                //            AgentDistributionRelation agentDistributionRelationSecond = new AgentDistributionRelationBLL().GetModel(agentinfoFirst.id);
                //            if (agentDistributionRelationSecond != null)
                //            {
                //                Agentinfo agentinfoSecond = _agentinfoBll.GetModel(agentDistributionRelationSecond.ParentAgentId);
                //                if (agentinfoSecond != null)
                //                {
                //                    XcxAppAccountRelation xcxAppAccountRelationSecond = _xcxappaccountrelationBll.GetModelByaccountidAndTid(agentinfoSecond.useraccountid, (int)TmpType.小未平台);
                //                    if (xcxAppAccountRelationSecond != null)
                //                    {
                //                        PlatStoreRelation platStoreRelationSecond = _platStoreRelationBLL.GetPlatStoreRelationOwner(xcxAppAccountRelationSecond.Id, platStore.Id, agentinfo.id);

                //                        platStoreRelationSecond.Category = platStore.Category;
                //                        platStoreRelationSecond.UpdateTime = DateTime.Now;
                //                        TranModel.Add(_platStoreRelationBLL.BuildUpdateSql(platStoreRelationSecond, "Category,UpdateTime"));
                //                    }
                //                }
                //            }
                //        }
                //    }
                //}
                #endregion


                if (TranModel.sqlArray != null && TranModel.sqlArray.Length > 0 && PlatStoreRelationBLL.SingleModel.ExecuteTransactionDataCorect(TranModel.sqlArray))
                {
                    returnObj.isok = true;
                    returnObj.Msg  = "操作成功";
                    return(Json(returnObj));
                }
                else
                {
                    returnObj.Msg = "更新失败";
                    return(Json(returnObj));
                }
            }
            else
            {
                //平台入驻模式
                PlatStoreAddSetting platStoreAddSetting = PlatStoreAddSettingBLL.SingleModel.GetPlatStoreAddSetting(r.Id);
                int addWay             = platStoreAddSetting != null ? platStoreAddSetting.AddWay : 0;
                PlatStoreAddRules rule = new PlatStoreAddRules();
                if (addWay == 1)
                {
                    platStore.State = -1;
                    int ruleId = Context.GetRequestInt("ruleId", 0);
                    rule = PlatStoreAddRulesBLL.SingleModel.getRule(r.Id, ruleId);
                    if (rule == null)
                    {
                        returnObj.Msg = "入驻套餐不存在!";
                        return(Json(returnObj));
                    }

                    platStore.YearCount = rule.YearCount;
                    platStore.CostPrice = rule.CostPrice;
                }

                //表示入驻平台 需要将该入驻店铺同步到平台的1 2级代理商
                int storeId = Convert.ToInt32(PlatStoreBLL.SingleModel.Add(platStore));

                if (storeId > 0)
                {
                    #region 数据同步

                    //插入关系表  才算成功 店铺数据都是从关系表获取才算有效的
                    //1.先将入驻到平台的插入
                    PlatStoreRelation platStoreRelation = new PlatStoreRelation();
                    platStoreRelation.StoreId    = storeId;
                    platStoreRelation.State      = 1;
                    platStoreRelation.FromType   = 0;
                    platStoreRelation.Aid        = r.Id;
                    platStoreRelation.Category   = platStore.Category;
                    platStoreRelation.AgentId    = agentinfo != null ? agentinfo.id : agentInfoId;
                    platStoreRelation.AddTime    = DateTime.Now;
                    platStoreRelation.UpdateTime = DateTime.Now;
                    TranModel.Add(PlatStoreRelationBLL.SingleModel.BuildAddSql(platStoreRelation));
                    //2.查找上级代理
                    #region 暂时先屏蔽
                    //AgentDistributionRelation agentDistributionRelationFirst = new AgentDistributionRelationBLL().GetModel(agentinfo.id);
                    //if (agentDistributionRelationFirst != null)
                    //{
                    //    Agentinfo agentinfoFirst = _agentinfoBll.GetModel(agentDistributionRelationFirst.ParentAgentId);
                    //    if (agentinfoFirst != null)
                    //    {
                    //        XcxAppAccountRelation xcxAppAccountRelationFirst = _xcxappaccountrelationBll.GetModelByaccountidAndTid(agentinfoFirst.useraccountid, (int)TmpType.小未平台);
                    //        if (xcxAppAccountRelationFirst != null)
                    //        {
                    //            PlatStoreRelation platStoreRelationFist = new PlatStoreRelation();
                    //            platStoreRelationFist.StoreId = storeId;
                    //            platStoreRelationFist.State = 0;
                    //            platStoreRelationFist.FromType = 1;
                    //            platStoreRelationFist.Aid = xcxAppAccountRelationFirst.Id;
                    //            platStoreRelationFist.Category = platStore.Category;
                    //            platStoreRelationFist.AgentId = agentinfo.id;
                    //            platStoreRelationFist.AddTime = DateTime.Now;
                    //            platStoreRelationFist.UpdateTime = DateTime.Now;
                    //            TranModel.Add(_platStoreRelationBLL.BuildAddSql(platStoreRelationFist));

                    //            //3.查找上级的上级代理
                    //            AgentDistributionRelation agentDistributionRelationSecond = new AgentDistributionRelationBLL().GetModel(agentinfoFirst.id);
                    //            if (agentDistributionRelationSecond != null)
                    //            {
                    //                Agentinfo agentinfoSecond = _agentinfoBll.GetModel(agentDistributionRelationSecond.ParentAgentId);
                    //                if (agentinfoSecond != null)
                    //                {
                    //                    XcxAppAccountRelation xcxAppAccountRelationSecond = _xcxappaccountrelationBll.GetModelByaccountidAndTid(agentinfoSecond.useraccountid, (int)TmpType.小未平台);
                    //                    if (xcxAppAccountRelationSecond != null)
                    //                    {
                    //                        PlatStoreRelation platStoreRelationSecond = new PlatStoreRelation();
                    //                        platStoreRelationSecond.StoreId = storeId;
                    //                        platStoreRelationSecond.State = 0;
                    //                        platStoreRelationSecond.FromType = 1;
                    //                        platStoreRelationSecond.Aid = xcxAppAccountRelationSecond.Id;
                    //                        platStoreRelationSecond.Category = platStore.Category;
                    //                        platStoreRelationSecond.AgentId = agentinfo.id;
                    //                        platStoreRelationSecond.AddTime = DateTime.Now;
                    //                        platStoreRelationSecond.UpdateTime = DateTime.Now;
                    //                        TranModel.Add(_platStoreRelationBLL.BuildAddSql(platStoreRelationSecond));
                    //                    }

                    //                }
                    //            }


                    //        }
                    //    }
                    //}
                    #endregion



                    #endregion
                    int orderid = 0;
                    if (addWay == 1)
                    {
                        CityMorders order = new CityMorders()
                        {
                            FuserId        = storeId,
                            Fusername      = storeName,
                            TuserId        = 0,
                            OrderType      = (int)ArticleTypeEnum.PlatAddStorePay,
                            ActionType     = (int)miniAppBuyMode.微信支付,
                            Addtime        = DateTime.Now,
                            Percent        = 99,//不收取服务费
                            userip         = WebHelper.GetIP(),
                            payment_status = 0,
                            Status         = 0,
                            CitySubId      = 0,//无分销,默认为0
                            PayRate        = 1,
                            appid          = appId,
                            Articleid      = rule.Id,
                            CommentId      = platStore.YearCount,
                            MinisnsId      = r.Id,
                            payment_free   = platStore.CostPrice,
                            ShowNote       = $"平台版店铺入驻收费付款{platStore.CostPrice * 0.01}元"
                        };
                        string no = WxPayApi.GenerateOutTradeNo();
                        order.orderno  = no;
                        order.trade_no = no;

                        orderid = Convert.ToInt32(_cityMordersBLL.Add(order));
                    }



                    if (TranModel.sqlArray != null && TranModel.sqlArray.Length > 0)
                    {
                        if (PlatStoreRelationBLL.SingleModel.ExecuteTransactionDataCorect(TranModel.sqlArray))
                        {
                            if (orderid <= 0 && addWay == 1)
                            {
                                returnObj.Msg = "入驻失败(订单生成失败)";
                                return(Json(returnObj));
                            }

                            returnObj.dataObj = new { storeId = storeId, orderid = orderid };
                            returnObj.isok    = true;
                            returnObj.Msg     = "入驻成功";
                            return(Json(returnObj));
                        }
                        else
                        {
                            platStore.State      = -1;
                            platStore.UpdateTime = DateTime.Now;
                            PlatStoreBLL.SingleModel.Update(platStore, "State,UpdateTime");
                            returnObj.Msg = "入驻失败";
                            return(Json(returnObj));
                        }
                    }
                    else
                    {
                        returnObj.dataObj = storeId;
                        returnObj.isok    = true;
                        returnObj.Msg     = "入驻成功";
                        return(Json(returnObj));
                    }
                }
                else
                {
                    returnObj.Msg = "入驻失败(请联系客服)";
                    return(Json(returnObj));
                }
            }
        }
        /// <summary>
        /// Add a localized asset to the asset table.
        /// This function will ensure the localization system adds the asset to the Addressables system and sets the asset up for use.
        /// </summary>
        /// <param name="table">The table to add the asset to, must be part of the collection.</param>
        /// <param name="entryReference">The table entry Key or Key Id.</param>
        /// <param name="asset">The asset to add.</param>
        /// <param name="createUndo">Should an undo operation be created?</param>
        public virtual void AddAssetToTable(AssetTable table, TableEntryReference entryReference, Object asset, bool createUndo = false)
        {
            if (table == null)
            {
                throw new ArgumentNullException(nameof(table), "Can not add asset to null table");
            }

            if (asset == null)
            {
                throw new ArgumentNullException(nameof(asset), "Can not add null asset to table");
            }

            if (!ContainsTable(table))
            {
                throw new Exception("The table does not belong to this collection.");
            }

            if (!EditorUtility.IsPersistent(table))
            {
                throw new AssetNotPersistentException(table);
            }

            if (!EditorUtility.IsPersistent(asset))
            {
                throw new AssetNotPersistentException(asset);
            }

            // Add the asset to the Addressables system and setup the table with the key to guid mapping.
            var aaSettings = LocalizationEditorSettings.Instance.GetAddressableAssetSettings(true);

            if (aaSettings == null)
            {
                return;
            }

            var undoGroup = Undo.GetCurrentGroup();

            if (createUndo)
            {
                Undo.RecordObject(aaSettings, "Add asset to table");
            }

            // Remove the old asset first
            var assetGuid  = LocalizationEditorSettings.Instance.GetAssetGuid(asset);
            var tableEntry = table.GetEntryFromReference(entryReference);

            if (tableEntry != null)
            {
                if (tableEntry.Guid == assetGuid)
                {
                    return;
                }

                RemoveAssetFromTable(table, entryReference, createUndo);
            }

            // Has the asset already been added? Perhaps it is being used by multiple tables or the user has added it manually.
            var entry      = aaSettings.FindAssetEntry(assetGuid);
            var entryLabel = AddressHelper.FormatAssetLabel(table.LocaleIdentifier.Code);

            aaSettings.AddLabel(entryLabel);

            if (entry == null)
            {
                var group = LocalizationEditorSettings.Instance.GetGroup(aaSettings, FormatAssetTableCollectionName(table.LocaleIdentifier), true, createUndo);

                if (createUndo)
                {
                    Undo.RecordObject(group, "Add asset to table");
                }

                entry = aaSettings.CreateOrMoveEntry(assetGuid, group, true);
                entry.SetLabel(entryLabel, true);
                entry.address = LocalizationEditorSettings.Instance.FindUniqueAssetAddress(asset.name);
            }
            else
            {
                Undo.RecordObject(entry.parentGroup, "Add asset to table");
                entry.SetLabel(entryLabel, true);
                UpdateAssetGroup(aaSettings, entry, createUndo);
            }

            // Update the table
            if (createUndo)
            {
                Undo.RecordObject(table, "Add asset to table");
                Undo.RecordObject(table.SharedData, "Add asset to table");
            }
            //else // Asset changes are not being saved correctly at the moment when using Undo. (LOC-82)
            {
                EditorUtility.SetDirty(table);
                EditorUtility.SetDirty(table.SharedData);
            }

            tableEntry = table.AddEntryFromReference(entryReference, assetGuid);

            // Update type metadata
            AssetTypeMetadata entryMetadata = null;
            AssetTypeMetadata typeMetadata  = null;
            var assetType = asset.GetType();

            // We cant use a foreach here as we are sometimes inside of a loop and exceptions will be thrown (Collection was modified).
            for (int i = 0; i < table.SharedData.Metadata.MetadataEntries.Count; ++i)
            {
                var md = table.SharedData.Metadata.MetadataEntries[i];
                if (md is AssetTypeMetadata at)
                {
                    if (at.Contains(tableEntry.KeyId))
                    {
                        if (!at.Type.IsAssignableFrom(assetType))
                        {
                            tableEntry.RemoveSharedMetadata(at);

                            // Are other tables still using the type for the same id?
                            if (at.Contains(tableEntry.KeyId))
                            {
                                var name = SharedData.GetEntry(tableEntry.KeyId);
                                Debug.LogWarning($"Table entry {name}({tableEntry.KeyId}) contains mixed types. Both {at.Type} and {assetType} are used.");
                            }
                        }
                        else
                        {
                            entryMetadata = at;
                            break;
                        }
                    }

                    if (at.Type == assetType)
                    {
                        typeMetadata = at;
                        break;
                    }
                }
            }
            var foundMetadata = entryMetadata ?? typeMetadata;

            if (foundMetadata == null)
            {
                foundMetadata = new AssetTypeMetadata()
                {
                    Type = assetType
                };
            }
            tableEntry.AddSharedMetadata(foundMetadata);

            if (createUndo)
            {
                Undo.CollapseUndoOperations(undoGroup);
            }

            LocalizationEditorSettings.EditorEvents.RaiseAssetTableEntryAdded(this, table, tableEntry);
        }
Exemple #27
0
        public void LocaleLabelToId_CorrectlyConvertsLabel(string label, string expectedCode)
        {
            var localeId = AddressHelper.LocaleLabelToId(label);

            Assert.AreEqual(expectedCode, localeId.Code, "Failed to convert the Addressables Locale label to the correct LocaleIdentifier");
        }
Exemple #28
0
        /// <summary>
        /// 获取首页轮播图以及推荐商家
        /// </summary>
        /// <returns></returns>
        public ActionResult GetConfig()
        {
            returnObj      = new Return_Msg_APP();
            returnObj.code = "200";
            string appId = Context.GetRequest("appId", string.Empty);

            if (string.IsNullOrEmpty(appId))
            {
                returnObj.Msg = "参数错误";
                return(Json(returnObj));
            }

            int pageIndexAdImg   = Context.GetRequestInt("pageIndexAdImg", 1);
            int pageSizeAdImg    = Context.GetRequestInt("pageSizeAdImg", 10);
            int pageIndexTjStore = Context.GetRequestInt("pageIndexTjStore", 1);
            int pageSizeTjStore  = Context.GetRequestInt("pageSizeTjStore", 20);

            XcxAppAccountRelation r = _xcxAppAccountRelationBLL.GetModelByAppid(appId);

            if (r == null)
            {
                returnObj.Msg = "小程序未授权";
                return(Json(returnObj, JsonRequestBehavior.AllowGet));
            }

            string appname = "";
            OpenAuthorizerConfig openonfigmodel = OpenAuthorizerConfigBLL.SingleModel.GetModelByAppids(r.AppId);

            if (openonfigmodel != null)
            {
                appname = openonfigmodel.nick_name;
            }
            else
            {
                UserXcxTemplate userXcxModel = UserXcxTemplateBLL.SingleModel.GetModelByAppId(r.AppId);
                appname = userXcxModel?.Name;
            }
            int adImgCount, tjStoreCount = 0;
            List <PlatConfig> listADImg   = PlatConfigBLL.SingleModel.getListByaid(r.Id, out adImgCount, 0, pageSizeAdImg, pageIndexAdImg);
            List <PlatConfig> listTjStore = PlatConfigBLL.SingleModel.getListByaid(r.Id, out tjStoreCount, 1, pageSizeTjStore, pageIndexTjStore);

            string lngStr      = Context.GetRequest("lng", string.Empty);
            string latStr      = Context.GetRequest("lat", string.Empty);
            double lng         = 0.00;
            double lat         = 0.00;
            string curLocation = "未知城市";
            int    curCityCode = 0;

            if (!double.TryParse(lngStr, out lng) || !double.TryParse(latStr, out lat))
            {
                string IP = WebHelper.GetIP();

                IPToPoint iPToPoint = CommondHelper.GetLoctionByIP(IP);
                if (iPToPoint != null)
                {
                    lat    = iPToPoint.result.location.lat;
                    lng    = iPToPoint.result.location.lng;
                    lngStr = lng.ToString();
                    latStr = lat.ToString();
                    //log4net.LogHelper.WriteInfo(this.GetType(), $"IP={IP};{lat},{lng}");
                }
            }
            AddressApi addressinfo = AddressHelper.GetAddressByApi(lngStr, latStr);

            // log4net.LogHelper.WriteInfo(this.GetType(), Newtonsoft.Json.JsonConvert.SerializeObject(addressinfo));
            if (addressinfo != null && addressinfo.result != null && addressinfo.result.address_component != null)
            {
                curLocation = addressinfo.result.address_component.city;
                curCityCode = C_AreaBLL.SingleModel.GetCodeByName(curLocation);
            }


            listTjStore.ForEach(x =>
            {
                x.ObjName = x.ObjName.Length > 6 ? (x.ObjName.Substring(0, 5) + "...") : x.ObjName;
            });

            PlatConfig platConfigRemark = PlatConfigBLL.SingleModel.GetPlatConfig(r.Id, 3);
            var        remarkObj        = new { haveRemark = false, remark = string.Empty, remarkOpenFrm = false };

            if (platConfigRemark != null && !string.IsNullOrEmpty(platConfigRemark.ADImg))
            {
                remarkObj = new { haveRemark = true, remark = platConfigRemark.ADImg, remarkOpenFrm = platConfigRemark.ObjId == 0 };
            }

            PlatConfig platOther = PlatConfigBLL.SingleModel.GetPlatConfig(r.Id, 5);//获取平台其它设置

            if (platOther == null)
            {
                platOther = new PlatConfig()
                {
                    Aid = r.Id, AddTime = DateTime.Now, ConfigType = 5
                };
            }
            PlatOtherConfig platOtherConfig = new PlatOtherConfig();

            platOtherConfig.VirtualPV           = platOther.ADImgType;
            platOtherConfig.VirtualPlatMsgCount = platOther.ObjId;
            platOtherConfig.PlatMsgCount        = PlatMsgBLL.SingleModel.GetCountByAId(r.Id);
            platOtherConfig.PV = PlatStatisticalFlowBLL.SingleModel.GetPVCount(r.Id);

            int totalPV      = platOtherConfig.VirtualPV + platOtherConfig.PV;
            int totalMsgCout = platOtherConfig.PlatMsgCount + platOtherConfig.VirtualPlatMsgCount;

            PlatConfig platOfficialAccount = PlatConfigBLL.SingleModel.GetPlatConfig(r.Id, 6);//获取关注公众号设置

            if (platOfficialAccount == null)
            {
                platOfficialAccount = new PlatConfig()
                {
                    Aid = r.Id, AddTime = DateTime.Now, ConfigType = 6
                };
            }


            returnObj.dataObj = new
            {
                appname             = appname,
                ADImgs              = new { totalCount = adImgCount, list = listADImg },
                TjStores            = new { totalCount = tjStoreCount, list = listTjStore },
                Location            = new { curLocation = curLocation, curCityCode = curCityCode },
                platConfigRemark    = remarkObj,
                platOtherConfig     = new { TotalPV = totalPV > 100000?Convert.ToInt32(totalPV * 0.0001).ToString() + "万+": totalPV.ToString(), TotalMsgCount = totalMsgCout > 100000? Convert.ToInt32(totalMsgCout * 0.0001).ToString() + "万+": totalMsgCout.ToString() },
                platOfficialAccount = platOfficialAccount
            };
            returnObj.isok = true;
            returnObj.Msg  = "获取成功";
            return(Json(returnObj, JsonRequestBehavior.AllowGet));
        }
Exemple #29
0
        /// <summary>
        /// 创建名片
        /// </summary>
        /// <returns></returns>
        public ActionResult AddMyCard()
        {
            returnObj = new Return_Msg_APP();
            string imgUrl      = Context.GetRequest("imgurl", "");
            string companyName = Context.GetRequest("companyname", "");
            int    userId      = Context.GetRequestInt("userid", 0);
            int    jobType     = Context.GetRequestInt("jobtype", 0);
            string lat         = Context.GetRequest("lat", "0");
            string lng         = Context.GetRequest("lng", "0");
            string name        = Context.GetRequest("name", "");
            string address     = Context.GetRequest("address", "");
            string job         = Context.GetRequest("job", "");
            string department  = Context.GetRequest("department", "");
            string desc        = Context.GetRequest("desc", "");
            int    industryIid = Context.GetRequestInt("industryid", 0);
            int    hiddenPhone = Context.GetRequestInt("hiddenphone", 0);
            int    type        = Context.GetRequestInt("type", 0);

            if (userId <= 0)
            {
                returnObj.Msg = "userid不能小于0";
                return(Json(returnObj));
            }
            if (type == 1)
            {
                if (string.IsNullOrEmpty(lat))
                {
                    returnObj.Msg = "lat不能小于0";
                    return(Json(returnObj));
                }
                if (string.IsNullOrEmpty(lng))
                {
                    returnObj.Msg = "lng不能为空";
                    return(Json(returnObj));
                }
                if (string.IsNullOrEmpty(address))
                {
                    returnObj.Msg = "地址不能为空";
                    return(Json(returnObj));
                }
                if (string.IsNullOrEmpty(name))
                {
                    returnObj.Msg = "姓名不能为空";
                    return(Json(returnObj));
                }
                if (industryIid <= 0)
                {
                    returnObj.Msg = "请选择行业";
                    return(Json(returnObj));
                }
            }

            C_UserInfo userinfo = C_UserInfoBLL.SingleModel.GetModel(userId);

            if (userinfo == null)
            {
                returnObj.Msg = "用户已失效";
                return(Json(returnObj));
            }
            XcxAppAccountRelation xcxrelatiion = _xcxAppAccountRelationBLL.GetModelByAppid(userinfo.appId);

            if (xcxrelatiion == null)
            {
                returnObj.Msg = "模板已失效";
                return(Json(returnObj));
            }
            int aid = xcxrelatiion.Id;

            PlatMyCard platMyCardModel = PlatMyCardBLL.SingleModel.GetModelByUserId(userId, aid);

            //地址
            if (!string.IsNullOrEmpty(lng) && lng != "0" && !string.IsNullOrEmpty(lat) && lat != "0")
            {
                AddressApi addressinfo = AddressHelper.GetAddressByApi(lng, lat);
                if (addressinfo != null && addressinfo.result != null && addressinfo.result.address_component != null)
                {
                    string provinceName          = addressinfo.result.address_component.province;
                    string cityName              = addressinfo.result.address_component.city;
                    string countryName           = addressinfo.result.address_component.district;
                    Dictionary <string, int> dic = C_AreaBLL.SingleModel.GetAddressCode(provinceName, cityName, countryName);
                    if (platMyCardModel == null)
                    {
                        platMyCardModel = new PlatMyCard();
                    }
                    platMyCardModel.ProvinceCode = dic["provincename"];
                    platMyCardModel.ProvinceCode = dic["cityname"];
                    platMyCardModel.ProvinceCode = dic["countryName"];
                }
            }
            imgUrl = string.IsNullOrEmpty(imgUrl) ? userinfo.HeadImgUrl : imgUrl;
            //获取服务器商的图片路径
            bool isreload = false;

            imgUrl = WxUploadHelper.GetMyServerImgUrl(imgUrl, ref isreload);

            if (platMyCardModel == null || platMyCardModel.Id <= 0)
            {
                platMyCardModel             = new PlatMyCard();
                platMyCardModel.AddTime     = DateTime.Now;
                platMyCardModel.Address     = address;
                platMyCardModel.AId         = aid;
                platMyCardModel.CompanyName = companyName;
                platMyCardModel.Desc        = desc;
                platMyCardModel.ImgUrl      = imgUrl;
                platMyCardModel.JobType     = jobType;
                platMyCardModel.Lat         = Convert.ToDouble(lat);
                platMyCardModel.Lng         = Convert.ToDouble(lng);
                platMyCardModel.Name        = name;
                platMyCardModel.NickName    = userinfo.NickName;
                platMyCardModel.Phone       = userinfo.TelePhone;
                platMyCardModel.UpdateTime  = DateTime.Now;
                platMyCardModel.UserId      = userId;
                platMyCardModel.Job         = job;
                platMyCardModel.Department  = department;
                platMyCardModel.IndustryId  = industryIid;
                platMyCardModel.HiddenPhone = hiddenPhone;
                platMyCardModel.AppId       = userinfo.appId;
                platMyCardModel.Id          = Convert.ToInt32(PlatMyCardBLL.SingleModel.Add(platMyCardModel));
                returnObj.isok = platMyCardModel.Id > 0;
            }
            else
            {
                platMyCardModel.AddTime     = DateTime.Now;
                platMyCardModel.Address     = address;
                platMyCardModel.AId         = aid;
                platMyCardModel.CompanyName = companyName;
                platMyCardModel.Desc        = "";
                platMyCardModel.ImgUrl      = imgUrl;
                platMyCardModel.JobType     = jobType;
                platMyCardModel.Lat         = Convert.ToDouble(lat);
                platMyCardModel.Lng         = Convert.ToDouble(lng);
                platMyCardModel.Name        = name;
                platMyCardModel.NickName    = userinfo.NickName;
                platMyCardModel.Phone       = userinfo.TelePhone;
                platMyCardModel.UpdateTime  = DateTime.Now;
                platMyCardModel.UserId      = userId;
                platMyCardModel.IndustryId  = industryIid;
                platMyCardModel.HiddenPhone = hiddenPhone;
                if (!string.IsNullOrEmpty(job))
                {
                    platMyCardModel.Job = job;
                }
                if (!string.IsNullOrEmpty(department))
                {
                    platMyCardModel.Department = department;
                }
                if (!string.IsNullOrEmpty(companyName))
                {
                    platMyCardModel.CompanyName = companyName;
                }
                if (!string.IsNullOrEmpty(desc))
                {
                    platMyCardModel.Desc = desc;
                }
                returnObj.isok = PlatMyCardBLL.SingleModel.Update(platMyCardModel);
            }
            returnObj.Msg     = returnObj.isok ? "保存成功" : "保存失败";
            returnObj.dataObj = platMyCardModel;
            return(Json(returnObj));
        }
Exemple #30
0
        public void CreateReceipt(Receipt receipt, User user, bool isOddCreateHu)
        {
            log.Debug("Start create receipt");
            #region 查找所有的发货项,收货单打印模板,收货差异处理选项
            string      orderType       = null;
            Party       partyFrom       = null;
            Party       partyTo         = null;
            ShipAddress shipFrom        = null;
            ShipAddress shipTo          = null;
            string      dockDescription = null;
            string      receiptTemplate = null;
            string      huTemplate      = null;
            string      grGapTo         = null;
            IList <InProcessLocationDetail> inProcessLocationDetailList = new List <InProcessLocationDetail>();
            if (receipt.InProcessLocations != null && receipt.InProcessLocations.Count > 0)
            {
                foreach (InProcessLocation inProcessLocation in receipt.InProcessLocations)
                {
                    InProcessLocation currentIp = inProcessLocationMgr.LoadInProcessLocation(inProcessLocation.IpNo);
                    if (currentIp.Status == BusinessConstants.CODE_MASTER_STATUS_VALUE_CLOSE)
                    {
                        throw new BusinessErrorException("InProcessLocation.Error.StatusErrorWhenReceive", currentIp.Status, currentIp.IpNo);
                    }

                    if (orderType == null)
                    {
                        orderType = inProcessLocation.OrderType;
                    }

                    //判断OrderHead的PartyFrom是否一致
                    if (partyFrom == null)
                    {
                        partyFrom = inProcessLocation.PartyFrom;
                    }
                    else if (inProcessLocation.PartyFrom.Code != partyFrom.Code)
                    {
                        throw new BusinessErrorException("Order.Error.ReceiveOrder.PartyFromNotEqual");
                    }

                    //判断OrderHead的PartyFrom是否一致
                    if (partyTo == null)
                    {
                        partyTo = inProcessLocation.PartyTo;
                    }
                    else if (inProcessLocation.PartyTo.Code != partyTo.Code)
                    {
                        throw new BusinessErrorException("Order.Error.ReceiveOrder.PartyToNotEqual");
                    }

                    //判断OrderHead的ShipFrom是否一致
                    if (shipFrom == null)
                    {
                        shipFrom = inProcessLocation.ShipFrom;
                    }
                    else if (!AddressHelper.IsAddressEqual(inProcessLocation.ShipFrom, shipFrom))
                    {
                        throw new BusinessErrorException("Order.Error.ReceiveOrder.ShipFromNotEqual");
                    }

                    //判断OrderHead的ShipTo是否一致
                    if (shipTo == null)
                    {
                        shipTo = inProcessLocation.ShipTo;
                    }
                    else if (!AddressHelper.IsAddressEqual(inProcessLocation.ShipTo, shipTo))
                    {
                        throw new BusinessErrorException("Order.Error.ReceiveOrder.ShipToNotEqual");
                    }

                    if (dockDescription == null)
                    {
                        dockDescription = inProcessLocation.DockDescription;
                    }
                    else if (inProcessLocation.DockDescription != dockDescription)
                    {
                        throw new BusinessErrorException("Order.Error.ReceiveOrder.DockDescriptionNotEqual");
                    }

                    //判断收货单打印模板是否一致
                    if (receiptTemplate == null)
                    {
                        receiptTemplate = inProcessLocation.ReceiptTemplate;
                    }
                    else
                    {
                        if (inProcessLocation.ReceiptTemplate != null && inProcessLocation.ReceiptTemplate != receiptTemplate)
                        {
                            throw new BusinessErrorException("Order.Error.ReceiveOrder.ReceiptTemplateNotEqual");
                        }
                    }

                    //判断条码打印模板是否一致
                    if (huTemplate == null)
                    {
                        huTemplate = inProcessLocation.HuTemplate;
                    }
                    else
                    {
                        if (inProcessLocation.HuTemplate != null && inProcessLocation.HuTemplate != huTemplate)
                        {
                            throw new BusinessErrorException("Order.Error.ReceiveOrder.HuTemplateNotEqual");
                        }
                    }

                    #region 查找收货差异处理选项
                    if (grGapTo == null)
                    {
                        grGapTo = inProcessLocation.GoodsReceiptGapTo;
                    }
                    else
                    {
                        if (inProcessLocation.GoodsReceiptGapTo != null && inProcessLocation.GoodsReceiptGapTo != grGapTo)
                        {
                            throw new BusinessErrorException("Order.Error.ReceiveOrder.GoodsReceiptGapToNotEqual");
                        }
                    }
                    #endregion

                    IListHelper.AddRange <InProcessLocationDetail>(
                        inProcessLocationDetailList, this.inProcessLocationDetailMgr.GetInProcessLocationDetail(inProcessLocation));
                }
            }
            #endregion

            IList <ReceiptDetail> targetReceiptDetailList = receipt.ReceiptDetails;
            receipt.ReceiptDetails = null;   //清空Asn明细,稍后填充

            #region 创建收货单Head
            receipt.ReceiptNo       = numberControlMgr.GenerateNumber(BusinessConstants.CODE_PREFIX_RECEIPT);
            receipt.OrderType       = orderType;
            receipt.CreateDate      = DateTime.Now;
            receipt.CreateUser      = user;
            receipt.PartyFrom       = partyFrom;
            receipt.PartyTo         = partyTo;
            receipt.ShipFrom        = shipFrom;
            receipt.ShipTo          = shipTo;
            receipt.DockDescription = dockDescription;
            receipt.ReceiptTemplate = receiptTemplate;
            receipt.IsPrinted       = false;
            receipt.NeedPrint       = false;
            if (receipt.InProcessLocations != null && receipt.InProcessLocations.Count > 0)
            {
                foreach (InProcessLocation inProcessLocation in receipt.InProcessLocations)
                {
                    if (inProcessLocation.NeedPrintReceipt)
                    {
                        receipt.NeedPrint = true;
                        break;
                    }
                }
            }

            this.CreateReceipt(receipt);
            log.Debug("Create receipt " + receipt.ReceiptNo + " head successful");
            #endregion

            #region HU处理/入库操作/创建收货明细
            log.Debug("Start create receipt detail");
            IList <LocationLotDetail> inspectLocationLotDetailList = new List <LocationLotDetail>();
            foreach (ReceiptDetail receiptDetail in targetReceiptDetailList)
            {
                OrderLocationTransaction orderLocationTransaction = receiptDetail.OrderLocationTransaction;
                OrderDetail orderDetail = orderLocationTransaction.OrderDetail;
                OrderHead   orderHead   = orderDetail.OrderHead;

                if (orderHead.CreateHuOption == BusinessConstants.CODE_MASTER_CREATE_HU_OPTION_VALUE_GR &&
                    receiptDetail.HuId == null)         //如果订单设置为收货时创建Hu,但是收货时已经扫描过Hu了,按已扫描处理
                {
                    #region 收货时创建Hu
                    log.Debug("Create receipt detail with generate barcode.");
                    #region 生产本次收货+剩余零头生成Hu
                    decimal oddQty = 0;

                    if (!isOddCreateHu && orderDetail.HuLotSize.HasValue &&
                        orderHead.Type == BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_PRODUCTION)    //只有生产支持零头
                    {
                        #region 查找剩余零头 + 本次收货数是否能够生成Hu
                        Hu oddHu = this.CreateHuFromOdd(receiptDetail, user);
                        if (oddHu != null)
                        {
                            log.Debug("Generate barcode using odd qty.");
                            //如果零头生成了Hu,本次收货数会扣减
                            #region 创建Hu
                            IList <Hu> oddHuList = new List <Hu>();
                            oddHuList.Add(oddHu);
                            IList <ReceiptDetail> oddReceiptDetailList = this.receiptDetailMgr.CreateReceiptDetail(receipt, orderLocationTransaction, oddHuList);
                            log.Debug("Generate odd barcode successful.");
                            #endregion

                            #region 入库
                            IList <InventoryTransaction> inventoryTransactionList = this.locationMgr.InventoryIn(oddReceiptDetailList[0], user, receiptDetail.PutAwayBinCode);
                            log.Debug("odd Inventory in successful.");
                            #endregion

                            #region 是否检验
                            if (orderDetail.NeedInspection && orderHead.NeedInspection && orderHead.SubType == BusinessConstants.CODE_MASTER_ORDER_SUB_TYPE_VALUE_NML)
                            {
                                foreach (InventoryTransaction inventoryTransaction in inventoryTransactionList)
                                {
                                    LocationLotDetail locationLotDetail = this.locationLotDetailMgr.LoadLocationLotDetail(inventoryTransaction.LocationLotDetailId);
                                    locationLotDetail.CurrentInspectQty = locationLotDetail.Qty;
                                    inspectLocationLotDetailList.Add(locationLotDetail);
                                }
                            }
                            #endregion
                        }
                        #endregion

                        oddQty = receiptDetail.ReceivedQty.HasValue && orderDetail.HuLotSize.HasValue ?
                                 receiptDetail.ReceivedQty.Value % orderDetail.HuLotSize.Value : 0; //收货零头数
                        log.Debug("Receive odd qty is " + oddQty);

                        receiptDetail.ReceivedQty = receiptDetail.ReceivedQty.Value - oddQty; //收货数量凑整
                    }
                    #endregion

                    #region 满包装/零头创建Hu处理
                    if (receiptDetail.ReceivedQty.HasValue ||
                        receiptDetail.RejectedQty.HasValue ||
                        receiptDetail.ScrapQty.HasValue)
                    {
                        //创建Hu
                        IList <Hu> huList = this.huMgr.CreateHu(receiptDetail, user);
                        log.Debug("Create barcode successful.");

                        //创建收货项
                        IList <ReceiptDetail> receiptDetailList = this.receiptDetailMgr.CreateReceiptDetail(receipt, orderLocationTransaction, huList);
                        log.Debug("Create receipt detail successful.");

                        #region 如果还有次品或者废品收货,添加到收货列表
                        if ((receiptDetail.RejectedQty.HasValue && receiptDetail.RejectedQty > 0) ||
                            (receiptDetail.ScrapQty.HasValue && receiptDetail.ScrapQty > 0))
                        {
                            ReceiptDetail rejAndScrapReceiptDetail = new ReceiptDetail();
                            CloneHelper.CopyProperty(receiptDetail, rejAndScrapReceiptDetail);
                            rejAndScrapReceiptDetail.ReceivedQty    = null;
                            rejAndScrapReceiptDetail.PutAwayBinCode = null;
                            rejAndScrapReceiptDetail.Receipt        = receipt;

                            this.receiptDetailMgr.CreateReceiptDetail(rejAndScrapReceiptDetail);

                            receiptDetailList.Add(rejAndScrapReceiptDetail);
                            receipt.AddReceiptDetail(rejAndScrapReceiptDetail);
                        }
                        #endregion

                        foreach (ReceiptDetail huReceiptDetail in receiptDetailList)
                        {
                            #region 匹配ReceiptDetail和InProcessLocationDetail,Copy相关信息
                            if (orderHead.Type != BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_PRODUCTION)
                            {
                                IList <InProcessLocationDetail> matchInProcessLocationDetailList = OrderHelper.FindMatchInProcessLocationDetail(receiptDetail, inProcessLocationDetailList);
                                if (matchInProcessLocationDetailList != null && matchInProcessLocationDetailList.Count > 0)
                                {
                                    if (matchInProcessLocationDetailList.Count > 1)
                                    {
                                        //只有当ASN中包含条码,按数量收货,并收货后创建条码才有可能发生这种情况。
                                        //变态才这么干。
                                        log.Error("只有当ASN中包含条码,按数量收货,并收货后创建条码才有可能发生这种情况。");
                                        throw new BusinessErrorException("你是变态才这么设置。");
                                    }

                                    //如果找到匹配项,只可能有一个
                                    huReceiptDetail.PlannedBill   = matchInProcessLocationDetailList[0].PlannedBill;
                                    huReceiptDetail.IsConsignment = matchInProcessLocationDetailList[0].IsConsignment;
                                    huReceiptDetail.ShippedQty    = matchInProcessLocationDetailList[0].Qty;

                                    this.receiptDetailMgr.UpdateReceiptDetail(huReceiptDetail);
                                }

                                //收货创建HU,分配PlannedAmount,todo:考虑余数
                                huReceiptDetail.PlannedAmount = receiptDetail.PlannedAmount / receiptDetail.ReceivedQty.Value * huReceiptDetail.ReceivedQty.Value;
                            }
                            #endregion

                            #region 入库
                            IList <InventoryTransaction> inventoryTransactionList = this.locationMgr.InventoryIn(huReceiptDetail, user, receiptDetail.PutAwayBinCode);
                            log.Debug("Inventory in successful.");
                            #endregion

                            #region 是否检验
                            if (orderDetail.NeedInspection &&
                                orderHead.NeedInspection &&
                                orderHead.SubType == BusinessConstants.CODE_MASTER_ORDER_SUB_TYPE_VALUE_NML &&
                                huReceiptDetail.ReceivedQty.HasValue &&
                                huReceiptDetail.ReceivedQty > 0)
                            {
                                foreach (InventoryTransaction inventoryTransaction in inventoryTransactionList)
                                {
                                    if (inventoryTransaction.Location.Code != BusinessConstants.SYSTEM_LOCATION_REJECT)
                                    {
                                        LocationLotDetail locationLotDetail = this.locationLotDetailMgr.LoadLocationLotDetail(inventoryTransaction.LocationLotDetailId);
                                        locationLotDetail.CurrentInspectQty = inventoryTransaction.Qty;
                                        inspectLocationLotDetailList.Add(locationLotDetail);
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                    #endregion

                    #region 生产剩余零头处理
                    if (oddQty > 0)
                    {
                        log.Debug("Start handle odd qty.");
                        ReceiptDetail oddReceiptDetail = new ReceiptDetail();
                        CloneHelper.CopyProperty(receiptDetail, oddReceiptDetail);

                        oddReceiptDetail.ReceivedQty = oddQty;
                        oddReceiptDetail.RejectedQty = 0;
                        oddReceiptDetail.ScrapQty    = 0;

                        #region 零头入库
                        oddReceiptDetail.Receipt = receipt;
                        IList <InventoryTransaction> inventoryTransactionList = this.locationMgr.InventoryIn(oddReceiptDetail, user, receiptDetail.PutAwayBinCode);
                        #endregion

                        #region 零头创建收货明细
                        this.receiptDetailMgr.CreateReceiptDetail(oddReceiptDetail);
                        receipt.AddReceiptDetail(oddReceiptDetail);
                        #endregion

                        #region 创建HuOdd
                        LocationLotDetail locationLotDetail = locationLotDetailMgr.LoadLocationLotDetail(inventoryTransactionList[0].LocationLotDetailId);
                        this.huOddMgr.CreateHuOdd(oddReceiptDetail, locationLotDetail, user);
                        #endregion
                        log.Debug("End handle odd qty.");
                    }
                    #endregion

                    #endregion
                }
                else
                {
                    #region 收货时不创建Hu
                    log.Debug("Create receipt detail with no generate barcode.");

                    #region 更新Hu上的OrderNo、ReceiptNo和AntiResloveHu
                    if (receiptDetail.HuId != null && receiptDetail.HuId.Trim() != string.Empty)
                    {
                        Hu   hu        = this.huMgr.LoadHu(receiptDetail.HuId);
                        bool isUpdated = false;

                        if (hu.OrderNo == null || hu.ReceiptNo == null)
                        {
                            if (hu.OrderNo == null)
                            {
                                log.Debug("Update hu OrderNo " + orderHead.OrderNo + ".");
                                hu.OrderNo = orderHead.OrderNo;
                            }

                            if (hu.ReceiptNo == null)
                            {
                                log.Debug("Update hu ReceiptNo " + receipt.ReceiptNo + ".");
                                hu.ReceiptNo = receipt.ReceiptNo;
                            }

                            isUpdated = true;
                        }

                        if (hu.AntiResolveHu == null &&
                            orderHead.Type == BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_PROCUREMENT)
                        {
                            hu.AntiResolveHu = orderHead.AntiResolveHu;
                            isUpdated        = true;
                        }

                        if (isUpdated)
                        {
                            this.huMgr.UpdateHu(hu);
                        }
                    }
                    #endregion

                    IList <ReceiptDetail> noCreateHuReceiptDetailList = new List <ReceiptDetail>();

                    #region 匹配ReceiptDetail和InProcessLocationDetail,Copy相关信息
                    log.Debug("Start match ReceiptDetail and InProcessLocationDetail.");
                    if (orderHead.Type != BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_PRODUCTION &&
                        orderHead.SubType != BusinessConstants.CODE_MASTER_ORDER_SUB_TYPE_VALUE_ADJ)     //收货调整已经匹配过InProcessLocationDetail,不需要在匹配
                    {
                        IList <InProcessLocationDetail> matchInProcessLocationDetailList = OrderHelper.FindMatchInProcessLocationDetail(receiptDetail, inProcessLocationDetailList);
                        log.Debug("Find matched InProcessLocationDetailList, count = " + matchInProcessLocationDetailList != null ? matchInProcessLocationDetailList.Count : 0);

                        if (matchInProcessLocationDetailList != null && matchInProcessLocationDetailList.Count == 1)
                        {
                            //一次收货对应一次发货。
                            log.Debug("one ipdet vs one receiptdet.");
                            receiptDetail.PlannedBill   = matchInProcessLocationDetailList[0].PlannedBill;
                            receiptDetail.IsConsignment = matchInProcessLocationDetailList[0].IsConsignment;
                            if (matchInProcessLocationDetailList[0].InProcessLocation.Type == BusinessConstants.CODE_MASTER_INPROCESS_LOCATION_TYPE_VALUE_GAP)
                            {
                                receiptDetail.ShippedQty = 0 - matchInProcessLocationDetailList[0].Qty;
                            }
                            else
                            {
                                receiptDetail.ShippedQty = matchInProcessLocationDetailList[0].Qty;
                            }
                            receiptDetail.ReceivedInProcessLocationDetail = matchInProcessLocationDetailList[0];
                            noCreateHuReceiptDetailList.Add(receiptDetail);
                        }
                        else if (matchInProcessLocationDetailList != null && matchInProcessLocationDetailList.Count > 1)
                        {
                            //一次收货对应多次发货。
                            //如:发货按条码,收货按数量。
                            log.Debug("multi ipdet vs one receiptdet.");
                            decimal totalRecQty = receiptDetail.ReceivedQty.Value;
                            InProcessLocationDetail lastInProcessLocationDetail = null;
                            log.Debug("Start Fetch matched InProcessLocationDetailList.");
                            foreach (InProcessLocationDetail inProcessLocationDetail in matchInProcessLocationDetailList)
                            {
                                lastInProcessLocationDetail = inProcessLocationDetail; //记录最后一次发货项,供没有对应发货的收货项使用

                                if (inProcessLocationDetail.ReceivedQty.HasValue && Math.Abs(inProcessLocationDetail.ReceivedQty.Value) >= Math.Abs(inProcessLocationDetail.Qty))
                                {
                                    continue;
                                }

                                if (Math.Abs(totalRecQty) > 0)
                                {
                                    log.Debug("Start cloned ReceiptDetail.");
                                    ReceiptDetail clonedReceiptDetail = new ReceiptDetail();
                                    CloneHelper.CopyProperty(receiptDetail, clonedReceiptDetail);
                                    log.Debug("End cloned ReceiptDetail.");

                                    clonedReceiptDetail.PlannedBill   = inProcessLocationDetail.PlannedBill;
                                    clonedReceiptDetail.IsConsignment = inProcessLocationDetail.IsConsignment;

                                    #region
                                    if (matchInProcessLocationDetailList[0].InProcessLocation.Type == BusinessConstants.CODE_MASTER_INPROCESS_LOCATION_TYPE_VALUE_GAP)
                                    {
                                        inProcessLocationDetail.Qty = 0 - inProcessLocationDetail.Qty;
                                    }
                                    #endregion

                                    if (Math.Abs(totalRecQty) > Math.Abs(inProcessLocationDetail.Qty - (inProcessLocationDetail.ReceivedQty.HasValue ? inProcessLocationDetail.ReceivedQty.Value : decimal.Zero)))
                                    {
                                        clonedReceiptDetail.ReceivedQty = inProcessLocationDetail.Qty - (inProcessLocationDetail.ReceivedQty.HasValue ? inProcessLocationDetail.ReceivedQty.Value : decimal.Zero);
                                        clonedReceiptDetail.ShippedQty  = inProcessLocationDetail.Qty - (inProcessLocationDetail.ReceivedQty.HasValue ? inProcessLocationDetail.ReceivedQty.Value : decimal.Zero);
                                        totalRecQty -= inProcessLocationDetail.Qty - (inProcessLocationDetail.ReceivedQty.HasValue ? inProcessLocationDetail.ReceivedQty.Value : decimal.Zero);
                                    }
                                    else
                                    {
                                        clonedReceiptDetail.ReceivedQty = totalRecQty;
                                        clonedReceiptDetail.ShippedQty  = totalRecQty;
                                        totalRecQty = 0;
                                    }

                                    //因为去掉了数量,记录已经匹配的发货项,避免差异处理的时候匹配多条而产生差异。
                                    clonedReceiptDetail.ReceivedInProcessLocationDetail = inProcessLocationDetail;

                                    noCreateHuReceiptDetailList.Add(clonedReceiptDetail);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            log.Debug("End Fetch matched InProcessLocationDetailList.");

                            //超收,没有找到对应的发货项,只记录收货数,发货数记0
                            if (Math.Abs(totalRecQty) > 0)
                            {
                                ReceiptDetail clonedReceiptDetail = new ReceiptDetail();
                                CloneHelper.CopyProperty(receiptDetail, clonedReceiptDetail);

                                clonedReceiptDetail.ShippedQty  = 0;
                                clonedReceiptDetail.ReceivedQty = totalRecQty;
                                clonedReceiptDetail.ReceivedInProcessLocationDetail = lastInProcessLocationDetail;

                                noCreateHuReceiptDetailList.Add(clonedReceiptDetail);
                            }
                        }
                        else
                        {
                            noCreateHuReceiptDetailList.Add(receiptDetail);
                        }
                    }
                    else
                    {
                        noCreateHuReceiptDetailList.Add(receiptDetail);
                    }
                    log.Debug("End match ReceiptDetail and InProcessLocationDetail.");
                    #endregion

                    foreach (ReceiptDetail noCreateHuReceiptDetail in noCreateHuReceiptDetailList)
                    {
                        noCreateHuReceiptDetail.Receipt = receipt;

                        if (noCreateHuReceiptDetail.ReceivedQty != 0)
                        {
                            #region 入库
                            log.Debug("Start Inventory In.");
                            IList <InventoryTransaction> inventoryTransactionList = this.locationMgr.InventoryIn(noCreateHuReceiptDetail, user, noCreateHuReceiptDetail.PutAwayBinCode);
                            log.Debug("End Inventory In.");
                            #endregion

                            #region 是否检验
                            if (orderDetail.NeedInspection && orderHead.NeedInspection && inventoryTransactionList != null && inventoryTransactionList.Count > 0 &&
                                orderHead.SubType == BusinessConstants.CODE_MASTER_ORDER_SUB_TYPE_VALUE_NML)
                            {
                                foreach (InventoryTransaction inventoryTransaction in inventoryTransactionList)
                                {
                                    if (inventoryTransaction.Location.Code != BusinessConstants.SYSTEM_LOCATION_REJECT)
                                    {
                                        LocationLotDetail locationLotDetail = this.locationLotDetailMgr.LoadLocationLotDetail(inventoryTransaction.LocationLotDetailId);
                                        locationLotDetail.CurrentInspectQty = inventoryTransaction.Qty;
                                        inspectLocationLotDetailList.Add(locationLotDetail);
                                    }
                                }
                            }
                            #endregion
                        }

                        #region 创建收货明细
                        log.Debug("Start Create Receipt Detail.");
                        this.receiptDetailMgr.CreateReceiptDetail(noCreateHuReceiptDetail);
                        receipt.AddReceiptDetail(noCreateHuReceiptDetail);
                        log.Debug("End Create Receipt Detail.");
                        #endregion
                    }

                    #endregion
                }
            }
            #endregion

            #region 检验
            if (inspectLocationLotDetailList.Count > 0)
            {
                //对于没有Hu的,如果收货时已经回冲了负数库存,也就是库存数量和待检验数量不一致可能会有问题
                //增加ipno,receiptno,isseperated字段
                this.inspectOrderMgr.CreateInspectOrder(inspectLocationLotDetailList, user, receipt.InProcessLocations[0].IpNo, receipt.ReceiptNo, false);
            }
            #endregion

            //#region 匹配收货发货项,查找差异
            //IList<InProcessLocationDetail> gapInProcessLocationDetailList = new List<InProcessLocationDetail>();

            //#region 发货项不匹配
            //foreach (InProcessLocationDetail inProcessLocationDetail in inProcessLocationDetailList)
            //{
            //    if (inProcessLocationDetail.OrderLocationTransaction.OrderDetail.OrderHead.Type
            //        != BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_PRODUCTION)   //生产暂时不支持差异
            //    {
            //        decimal receivedQty = 0;  //发货项的累计收货数

            //        //一条发货项可能对应多条收货项
            //        foreach (ReceiptDetail receiptDetail in receipt.ReceiptDetails)
            //        {
            //            //匹配收货项和发货项
            //            if (receiptDetail.ReceivedInProcessLocationDetail != null)
            //            {
            //                //对于已经匹配的,直接按发货项匹配
            //                if (receiptDetail.ReceivedInProcessLocationDetail.Id == inProcessLocationDetail.Id)
            //                {
            //                    if (receiptDetail.ReceivedQty.HasValue)
            //                    {
            //                        receivedQty += receiptDetail.ReceivedQty.Value;
            //                    }
            //                }
            //            }
            //            else if (OrderHelper.IsInProcessLocationDetailMatchReceiptDetail(
            //                inProcessLocationDetail, receiptDetail))
            //            {
            //                if (receiptDetail.ReceivedQty.HasValue)
            //                {
            //                    receivedQty += receiptDetail.ReceivedQty.Value;
            //                }
            //            }
            //        }

            //        if (receivedQty != inProcessLocationDetail.Qty)
            //        {
            //            #region 收货数量和发货数量不匹配,记录差异
            //            InProcessLocationDetail gapInProcessLocationDetail = new InProcessLocationDetail();
            //            gapInProcessLocationDetail.Qty = receivedQty - inProcessLocationDetail.Qty;
            //            gapInProcessLocationDetail.OrderLocationTransaction = inProcessLocationDetail.OrderLocationTransaction;
            //            //gapInProcessLocationDetail.HuId = inProcessLocationDetail.HuId;
            //            gapInProcessLocationDetail.LotNo = inProcessLocationDetail.LotNo;
            //            gapInProcessLocationDetail.IsConsignment = inProcessLocationDetail.IsConsignment;
            //            gapInProcessLocationDetail.PlannedBill = inProcessLocationDetail.PlannedBill;

            //            gapInProcessLocationDetailList.Add(gapInProcessLocationDetail);
            //            #endregion
            //        }
            //    }
            //}
            //#endregion

            //#region 收货项不匹配
            //foreach (ReceiptDetail receiptDetail in receipt.ReceiptDetails)
            //{
            //    if (receiptDetail.OrderLocationTransaction.OrderDetail.OrderHead.Type
            //        != BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_PRODUCTION)   //生产暂时不支持差异
            //    {
            //        IList<InProcessLocationDetail> matchInProcessLocationDetailList = OrderHelper.FindMatchInProcessLocationDetail(receiptDetail, inProcessLocationDetailList);

            //        if (matchInProcessLocationDetailList == null || matchInProcessLocationDetailList.Count == 0)
            //        {
            //            OrderLocationTransaction outOrderLocationTransaction =
            //                this.orderLocationTransactionMgr.GetOrderLocationTransaction(receiptDetail.OrderLocationTransaction.OrderDetail, BusinessConstants.IO_TYPE_OUT)[0];
            //            #region 没有找到和收货项对应的发货项
            //            InProcessLocationDetail gapInProcessLocationDetail = new InProcessLocationDetail();
            //            gapInProcessLocationDetail.Qty = receiptDetail.ReceivedQty.Value;
            //            gapInProcessLocationDetail.OrderLocationTransaction = outOrderLocationTransaction;
            //            //gapInProcessLocationDetail.HuId = receiptDetail.HuId;
            //            gapInProcessLocationDetail.LotNo = receiptDetail.LotNo;
            //            gapInProcessLocationDetail.IsConsignment = receiptDetail.IsConsignment;
            //            gapInProcessLocationDetail.PlannedBill = receiptDetail.PlannedBill;

            //            gapInProcessLocationDetailList.Add(gapInProcessLocationDetail);
            //            #endregion
            //        }
            //    }
            //}
            //#endregion
            //#endregion

            #region 关闭InProcessLocation
            if (receipt.InProcessLocations != null && receipt.InProcessLocations.Count > 0)
            {
                foreach (InProcessLocation inProcessLocation in receipt.InProcessLocations)
                {
                    if (inProcessLocation.IsAsnUniqueReceipt)
                    {
                        //不支持多次收货直接关闭
                        this.inProcessLocationMgr.CloseInProcessLocation(inProcessLocation, user);
                    }
                    else
                    {
                        this.inProcessLocationMgr.TryCloseInProcessLocation(inProcessLocation, user);
                    }

                    //transportationOrderMgr.TryCompleteTransportationOrder(inProcessLocation, user);
                }
            }
            #endregion
        }
Exemple #31
0
        private void AddOrUpdatePartnerAddress(Partner partner, ICollection <AddressBook> addCollection, bool donotupdatelegaladdress)
        {
            if (partner == null || addCollection == null || addCollection.Count == 0)
            {
                return;
            }

            if (partner.Address == null || partner.Address.Count == 0)
            {
                //У партнера нет адреса

                var result = new List <AddressBook>();
                //Выбираем все не юридические адреса
                var adrs = addCollection.Where(p => p.ADDRESSBOOKTYPECODE != AddressBookType.ADR_LEGAL.ToString()).ToArray();
                if (adrs.Length > 0)
                {
                    result.AddRange(adrs);
                }

                //Добавляем только один юр. адрес
                var adrlegal = addCollection.FirstOrDefault(p => p.ADDRESSBOOKTYPECODE == AddressBookType.ADR_LEGAL.ToString());
                if (adrlegal != null)
                {
                    result.Add(adrlegal);
                }

                if (result.Count > 0)
                {
                    partner.Address = new WMSBusinessCollection <AddressBook>(result);
                }
            }
            else
            {
                //У партнера есть адрес

                //Получим список новых адресов
                var newaddreses = addCollection.Where(p => AddressHelper.FindAddressInCollection(partner.Address, p) == null).ToArray();

                //Добавляем все новые не юридические адреса
                var adrs = newaddreses.Where(p => p.ADDRESSBOOKTYPECODE != AddressBookType.ADR_LEGAL.ToString()).ToArray();
                if (adrs.Length > 0)
                {
                    partner.Address.AddRange(adrs);
                }

                //Ищем новый юридический адрес
                var adrlegal = newaddreses.FirstOrDefault(p => p.ADDRESSBOOKTYPECODE == AddressBookType.ADR_LEGAL.ToString());
                if (adrlegal != null)
                {
                    var existsadrlegal = AddressHelper.GetAddressWithMaxIdByType(partner.Address, AddressBookType.ADR_LEGAL.ToString());
                    if (existsadrlegal != null)
                    {
                        if (!donotupdatelegaladdress)
                        {
                            //Будем обновлять юр. адрес по макс. id
                            var id = existsadrlegal.GetKey <decimal>();
                            MapTo(adrlegal, existsadrlegal);
                            existsadrlegal.SetProperty(existsadrlegal.GetPrimaryKeyPropertyName(), id);
                        }
                    }
                    else
                    {
                        //Добавляем
                        partner.Address.Add(adrlegal);
                    }
                }
            }
        }